"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const setAssetRequirements_1 = require("../setAssetRequirements");
const mocks_1 = require("../../../testUtils/mocks");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/SecurityToken', require("../../../testUtils/mocks/entities").mockSecurityTokenModule('~/api/entities/SecurityToken'));
describe('setAssetRequirements procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let requirementToComplianceRequirementStub;
    let complianceRequirementToRequirementStub;
    let assetCompliancesStub;
    let ticker;
    let requirements;
    let rawTicker;
    let senderConditions;
    let receiverConditions;
    let rawComplianceRequirement;
    let args;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks();
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        requirementToComplianceRequirementStub = sinon_1.default.stub(utilsConversionModule, 'requirementToComplianceRequirement');
        complianceRequirementToRequirementStub = sinon_1.default.stub(utilsConversionModule, 'complianceRequirementToRequirement');
        ticker = 'someTicker';
        requirements = [
            ['condition0', 'condition1'],
            ['condition1', 'condition2', 'condition3'],
            ['condition4'],
        ];
        senderConditions = [
            'senderConditions0',
            'senderConditions1',
            'senderConditions2',
        ];
        receiverConditions = [
            'receiverConditions0',
            'receiverConditions1',
            'receiverConditions2',
        ];
        rawComplianceRequirement = senderConditions.map((sConditions, index) => ({
            /* eslint-disable @typescript-eslint/naming-convention */
            sender_conditions: sConditions,
            receiver_conditions: receiverConditions[index],
            /* eslint-enable @typescript-eslint/naming-convention */
        }));
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        /* eslint-enable @typescript-eslint/naming-convention */
        args = {
            ticker,
            requirements,
        };
    });
    let addTransactionStub;
    let resetAssetComplianceTransaction;
    let addComplianceRequirementTransaction;
    beforeEach(() => {
        mocks_1.dsMockUtils.setConstMock('complianceManager', 'maxConditionComplexity', {
            returnValue: mocks_1.dsMockUtils.createMockU32(50),
        });
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        assetCompliancesStub = mocks_1.dsMockUtils.createQueryStub('complianceManager', 'assetCompliances', {
            returnValue: [],
        });
        resetAssetComplianceTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'resetAssetCompliance');
        addComplianceRequirementTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'addComplianceRequirement');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        requirements.forEach((condition, index) => {
            const complianceRequirement = mocks_1.dsMockUtils.createMockComplianceRequirement({
                /* eslint-disable @typescript-eslint/naming-convention */
                sender_conditions: senderConditions[index],
                receiver_conditions: receiverConditions[index],
                id: mocks_1.dsMockUtils.createMockU32(1),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            requirementToComplianceRequirementStub
                .withArgs({ conditions: condition, id: 1 }, mockContext)
                .returns(complianceRequirement);
            complianceRequirementToRequirementStub
                .withArgs(sinon_1.default.match({
                /* eslint-disable @typescript-eslint/naming-convention */
                sender_conditions: senderConditions[index],
                receiver_conditions: receiverConditions[index],
                /* eslint-enable @typescript-eslint/naming-convention */
            }), mockContext)
                .returns({ conditions: condition, id: 1 });
        });
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.entityMockUtils.cleanup();
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if condition limit is reached', () => {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(setAssetRequirements_1.prepareSetAssetRequirements.call(proc, {
            ticker,
            requirements: new Array(50),
        })).rejects.toThrow('Condition limit reached');
    });
    test('should throw an error if the new list is the same as the current one', () => {
        assetCompliancesStub.withArgs(rawTicker).returns({
            requirements: rawComplianceRequirement,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        return expect(setAssetRequirements_1.prepareSetAssetRequirements.call(proc, args)).rejects.toThrow('The supplied condition list is equal to the current one');
    });
    test('should add a reset asset compliance transaction and add compliance requirement transactions to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentComplianceRequirement = rawComplianceRequirement.slice(0, -1);
        assetCompliancesStub.withArgs(rawTicker).returns({
            requirements: currentComplianceRequirement,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield setAssetRequirements_1.prepareSetAssetRequirements.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub.firstCall, resetAssetComplianceTransaction, {}, rawTicker);
        senderConditions.forEach((sConditions, index) => {
            sinon_1.default.assert.calledWith(addTransactionStub.getCall(index + 1), addComplianceRequirementTransaction, {}, rawTicker, sConditions, receiverConditions[index]);
        });
        expect(result).toMatchObject(mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }));
    }));
    test('should not add a remove claim issuers transaction if there are no default claim issuers set on the token', () => __awaiter(void 0, void 0, void 0, function* () {
        assetCompliancesStub.withArgs(rawTicker).returns({
            requirements: [],
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield setAssetRequirements_1.prepareSetAssetRequirements.call(proc, args);
        senderConditions.forEach((sConditions, index) => {
            sinon_1.default.assert.calledWith(addTransactionStub.getCall(index), addComplianceRequirementTransaction, {}, rawTicker, sConditions, receiverConditions[index]);
        });
        sinon_1.default.assert.callCount(addTransactionStub, senderConditions.length);
        expect(result).toMatchObject(mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }));
    }));
    test('should not add an asset compliance transactions if there are no claim issuers passed as arguments', () => __awaiter(void 0, void 0, void 0, function* () {
        const currentComplianceRequirement = rawComplianceRequirement;
        assetCompliancesStub.withArgs(rawTicker).returns({
            requirements: currentComplianceRequirement,
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield setAssetRequirements_1.prepareSetAssetRequirements.call(proc, Object.assign(Object.assign({}, args), { requirements: [] }));
        sinon_1.default.assert.calledWith(addTransactionStub.firstCall, resetAssetComplianceTransaction, {}, rawTicker);
        sinon_1.default.assert.calledOnce(addTransactionStub);
        expect(result).toMatchObject(mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker }));
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = setAssetRequirements_1.getAuthorization.bind(proc);
            const params = {
                ticker,
            };
            expect(boundFunc(params)).toEqual({
                permissions: {
                    transactions: [
                        types_1.TxTags.complianceManager.ResetAssetCompliance,
                        types_1.TxTags.complianceManager.AddComplianceRequirement,
                    ],
                    tokens: [mocks_1.entityMockUtils.getSecurityTokenInstance({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=setAssetRequirements.js.map