"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 bignumber_js_1 = __importDefault(require("bignumber.js"));
const types_1 = require("../../../polkadot/types");
const sinon_1 = __importDefault(require("sinon"));
const setAssetRequirements_1 = require("../setAssetRequirements");
const mocks_1 = require("../../../testUtils/mocks");
const types_2 = require("../../../types");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
describe('setAssetRequirements procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let requirementToComplianceRequirementStub;
    let ticker;
    let requirements;
    let currentRequirements;
    let rawTicker;
    let senderConditions;
    let receiverConditions;
    let rawComplianceRequirements;
    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');
        ticker = 'someTicker';
        requirements = [
            [
                {
                    type: types_2.ConditionType.IsIdentity,
                    identity: mocks_1.entityMockUtils.getIdentityInstance(),
                    target: types_2.ConditionTarget.Both,
                },
                {
                    type: types_2.ConditionType.IsExternalAgent,
                    target: types_2.ConditionTarget.Both,
                },
            ],
            [
                {
                    type: types_2.ConditionType.IsExternalAgent,
                    target: types_2.ConditionTarget.Both,
                },
                {
                    type: types_2.ConditionType.IsNoneOf,
                    claims: [],
                    target: types_2.ConditionTarget.Both,
                },
                {
                    type: types_2.ConditionType.IsAnyOf,
                    claims: [],
                    target: types_2.ConditionTarget.Both,
                },
            ],
            [
                {
                    type: types_2.ConditionType.IsPresent,
                    claim: {
                        type: types_2.ClaimType.NoData,
                    },
                    target: types_2.ConditionTarget.Both,
                },
            ],
        ];
        currentRequirements = requirements.map((conditions, index) => ({
            conditions,
            id: new bignumber_js_1.default(index),
        }));
        senderConditions = [
            'senderConditions0',
            'senderConditions1',
            'senderConditions2',
        ];
        receiverConditions = [
            'receiverConditions0',
            'receiverConditions1',
            'receiverConditions2',
        ];
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        /* eslint-enable @typescript-eslint/naming-convention */
        args = {
            ticker,
            requirements,
        };
    });
    let addTransactionStub;
    let resetAssetComplianceTransaction;
    let replaceAssetComplianceTransaction;
    beforeEach(() => {
        mocks_1.dsMockUtils.setConstMock('complianceManager', 'maxConditionComplexity', {
            returnValue: mocks_1.dsMockUtils.createMockU32(new bignumber_js_1.default(50)),
        });
        mocks_1.entityMockUtils.configureMocks({
            assetOptions: {
                complianceRequirementsGet: {
                    requirements: currentRequirements,
                    defaultTrustedClaimIssuers: [],
                },
            },
        });
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        resetAssetComplianceTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'resetAssetCompliance');
        replaceAssetComplianceTransaction = mocks_1.dsMockUtils.createTxStub('complianceManager', 'replaceAssetCompliance');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        rawComplianceRequirements = [];
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        requirements.forEach((conditions, 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(new bignumber_js_1.default(index)),
                /* eslint-enable @typescript-eslint/naming-convention */
            });
            rawComplianceRequirements.push(complianceRequirement);
            requirementToComplianceRequirementStub
                .withArgs({ conditions, id: new bignumber_js_1.default(index) }, mockContext)
                .returns(complianceRequirement);
        });
    });
    afterEach(() => {
        mocks_1.entityMockUtils.reset();
        mocks_1.procedureMockUtils.reset();
        mocks_1.dsMockUtils.reset();
    });
    afterAll(() => {
        mocks_1.procedureMockUtils.cleanup();
        mocks_1.dsMockUtils.cleanup();
    });
    test('should throw an error if the new list is the same as the current one', () => {
        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 to the queue if the new requirements are empty', () => __awaiter(void 0, void 0, void 0, function* () {
        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, {
            transaction: resetAssetComplianceTransaction,
            args: [rawTicker],
        });
        sinon_1.default.assert.calledOnce(addTransactionStub);
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should add a replace asset compliance transactions to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        mocks_1.entityMockUtils.configureMocks({
            assetOptions: {
                complianceRequirementsGet: {
                    requirements: currentRequirements.slice(0, 1),
                    defaultTrustedClaimIssuers: [],
                },
            },
        });
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
        const result = yield setAssetRequirements_1.prepareSetAssetRequirements.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub, {
            transaction: replaceAssetComplianceTransaction,
            args: [rawTicker, rawComplianceRequirements],
        });
        expect(result).toEqual(expect.objectContaining({ 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,
                requirements: [],
            };
            expect(boundFunc(params)).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.complianceManager.ResetAssetCompliance],
                    assets: [expect.objectContaining({ ticker })],
                    portfolios: [],
                },
            });
            expect(boundFunc(Object.assign(Object.assign({}, params), { requirements: [1] }))).toEqual({
                permissions: {
                    transactions: [types_1.TxTags.complianceManager.ReplaceAssetCompliance],
                    assets: [expect.objectContaining({ ticker })],
                    portfolios: [],
                },
            });
        });
    });
});
//# sourceMappingURL=setAssetRequirements.js.map