"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 setAssetDocuments_1 = require("../setAssetDocuments");
const mocks_1 = require("../../../testUtils/mocks");
const utils_1 = require("../../../types/utils");
const utilsConversionModule = __importStar(require("../../../utils/conversion"));
jest.mock('~/api/entities/Asset', require("../../../testUtils/mocks/entities").mockAssetModule('~/api/entities/Asset'));
describe('setAssetDocuments procedure', () => {
    let mockContext;
    let stringToTickerStub;
    let assetDocumentToDocumentStub;
    let ticker;
    let documents;
    let rawTicker;
    let rawDocuments;
    let documentEntries;
    let args;
    beforeAll(() => {
        mocks_1.dsMockUtils.initMocks({
            contextOptions: {
                balance: {
                    free: new bignumber_js_1.default(500),
                    locked: new bignumber_js_1.default(0),
                    total: new bignumber_js_1.default(500),
                },
            },
        });
        mocks_1.procedureMockUtils.initMocks();
        mocks_1.entityMockUtils.initMocks();
        stringToTickerStub = sinon_1.default.stub(utilsConversionModule, 'stringToTicker');
        sinon_1.default.stub(utilsConversionModule, 'signerValueToSignatory');
        assetDocumentToDocumentStub = sinon_1.default.stub(utilsConversionModule, 'assetDocumentToDocument');
        ticker = 'someTicker';
        documents = [
            {
                name: 'someDocument',
                uri: 'someUri',
                contentHash: '0x01',
            },
            {
                name: 'otherDocument',
                uri: 'otherUri',
                contentHash: '0x02',
            },
        ];
        rawTicker = mocks_1.dsMockUtils.createMockTicker(ticker);
        rawDocuments = documents.map(({ name, uri, contentHash, type, filedAt }) => mocks_1.dsMockUtils.createMockDocument({
            name: mocks_1.dsMockUtils.createMockDocumentName(name),
            uri: mocks_1.dsMockUtils.createMockDocumentUri(uri),
            /* eslint-disable @typescript-eslint/naming-convention */
            content_hash: mocks_1.dsMockUtils.createMockDocumentHash({
                H128: mocks_1.dsMockUtils.createMockU8aFixed(contentHash, true),
            }),
            doc_type: mocks_1.dsMockUtils.createMockOption(type ? mocks_1.dsMockUtils.createMockDocumentType(type) : null),
            filing_date: mocks_1.dsMockUtils.createMockOption(filedAt ? mocks_1.dsMockUtils.createMockMoment(new bignumber_js_1.default(filedAt.getTime())) : null),
            /* eslint-enabled @typescript-eslint/naming-convention */
        }));
        documentEntries = rawDocuments.map((doc, index) => utils_1.tuple([rawTicker, mocks_1.dsMockUtils.createMockU32(new bignumber_js_1.default(index))], doc));
        args = {
            ticker,
            documents,
        };
    });
    let addTransactionStub;
    let removeDocumentsTransaction;
    let addDocumentsTransaction;
    beforeEach(() => {
        addTransactionStub = mocks_1.procedureMockUtils.getAddTransactionStub();
        mocks_1.dsMockUtils.createQueryStub('asset', 'assetDocuments', {
            entries: [documentEntries[0]],
        });
        removeDocumentsTransaction = mocks_1.dsMockUtils.createTxStub('asset', 'removeDocuments');
        addDocumentsTransaction = mocks_1.dsMockUtils.createTxStub('asset', 'addDocuments');
        mockContext = mocks_1.dsMockUtils.getContextInstance();
        stringToTickerStub.withArgs(ticker, mockContext).returns(rawTicker);
        documents.forEach((doc, index) => {
            assetDocumentToDocumentStub.withArgs(doc, mockContext).returns(rawDocuments[index]);
        });
    });
    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, {
            currentDocs: documents,
            currentDocIds: [],
        });
        return expect(setAssetDocuments_1.prepareSetAssetDocuments.call(proc, args)).rejects.toThrow('The supplied document list is equal to the current one');
    });
    test('should add a remove documents transaction and an add documents transaction to the queue', () => __awaiter(void 0, void 0, void 0, function* () {
        const docIds = [documentEntries[0][0][1]];
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            currentDocIds: docIds,
            currentDocs: [],
        });
        const result = yield setAssetDocuments_1.prepareSetAssetDocuments.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub.firstCall, {
            transaction: removeDocumentsTransaction,
            feeMultiplier: new bignumber_js_1.default(1),
            args: [docIds, rawTicker],
        });
        sinon_1.default.assert.calledWith(addTransactionStub.secondCall, {
            transaction: addDocumentsTransaction,
            feeMultiplier: new bignumber_js_1.default(rawDocuments.length),
            args: [rawDocuments, rawTicker],
        });
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should not add a remove documents transaction if there are no documents linked to the Asset', () => __awaiter(void 0, void 0, void 0, function* () {
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            currentDocIds: [],
            currentDocs: [],
        });
        const result = yield setAssetDocuments_1.prepareSetAssetDocuments.call(proc, args);
        sinon_1.default.assert.calledWith(addTransactionStub.firstCall, {
            transaction: addDocumentsTransaction,
            feeMultiplier: new bignumber_js_1.default(rawDocuments.length),
            args: [rawDocuments, rawTicker],
        });
        sinon_1.default.assert.calledOnce(addTransactionStub);
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    test('should not add an add documents transaction if there are no documents passed as arguments', () => __awaiter(void 0, void 0, void 0, function* () {
        const docIds = [documentEntries[0][0][1]];
        const proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
            currentDocs: [documents[0]],
            currentDocIds: docIds,
        });
        const result = yield setAssetDocuments_1.prepareSetAssetDocuments.call(proc, Object.assign(Object.assign({}, args), { documents: [] }));
        sinon_1.default.assert.calledWith(addTransactionStub.firstCall, {
            transaction: removeDocumentsTransaction,
            feeMultiplier: new bignumber_js_1.default(1),
            args: [docIds, rawTicker],
        });
        sinon_1.default.assert.calledOnce(addTransactionStub);
        expect(result).toEqual(expect.objectContaining({ ticker }));
    }));
    describe('getAuthorization', () => {
        test('should return the appropriate roles and permissions', () => {
            let proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                currentDocIds: [documentEntries[0][0][1]],
                currentDocs: [],
            });
            let boundFunc = setAssetDocuments_1.getAuthorization.bind(proc);
            expect(boundFunc(args)).toEqual({
                permissions: {
                    assets: [expect.objectContaining({ ticker })],
                    transactions: [types_1.TxTags.asset.AddDocuments, types_1.TxTags.asset.RemoveDocuments],
                    portfolios: [],
                },
            });
            proc = mocks_1.procedureMockUtils.getInstance(mockContext, {
                currentDocIds: [],
                currentDocs: [],
            });
            boundFunc = setAssetDocuments_1.getAuthorization.bind(proc);
            expect(boundFunc(Object.assign(Object.assign({}, args), { documents: [] }))).toEqual({
                permissions: {
                    assets: [expect.objectContaining({ ticker })],
                    transactions: [],
                    portfolios: [],
                },
            });
        });
    });
    describe('prepareStorage', () => {
        test('should return the current documents and their ids', () => __awaiter(void 0, void 0, void 0, function* () {
            const proc = mocks_1.procedureMockUtils.getInstance(mockContext);
            const boundFunc = setAssetDocuments_1.prepareStorage.bind(proc);
            mocks_1.dsMockUtils.createQueryStub('asset', 'assetDocuments', {
                entries: documentEntries,
            });
            const result = yield boundFunc(args);
            expect(result).toEqual({
                currentDocs: documents,
                currentDocIds: documentEntries.map(([[, id]]) => id),
            });
        }));
    });
});
//# sourceMappingURL=setAssetDocuments.js.map