"use strict";
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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setTokenDocuments = exports.prepareStorage = exports.getAuthorization = exports.prepareSetTokenDocuments = void 0;
const lodash_1 = require("lodash");
const types_1 = require("../../polkadot/types");
const internal_1 = require("../../internal");
const types_2 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
function prepareSetTokenDocuments(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, storage: { currentDocIds, currentDocs }, } = this;
        const { ticker, documents } = args;
        if (!lodash_1.differenceWith(currentDocs, documents, lodash_1.isEqual).length &&
            currentDocs.length === documents.length) {
            throw new internal_1.PolymeshError({
                code: types_2.ErrorCode.NoDataChange,
                message: 'The supplied document list is equal to the current one',
            });
        }
        const rawDocuments = documents.map(doc => conversion_1.tokenDocumentToDocument(doc, context));
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        if (currentDocIds.length) {
            internal_2.batchArguments(currentDocIds, types_1.TxTags.asset.RemoveDocuments).forEach(docIdBatch => {
                this.addTransaction(tx.asset.removeDocuments, { batchSize: docIdBatch.length }, docIdBatch, rawTicker);
            });
        }
        if (rawDocuments.length) {
            internal_2.batchArguments(rawDocuments, types_1.TxTags.asset.AddDocuments).forEach(rawDocumentBatch => {
                this.addTransaction(tx.asset.addDocuments, { batchSize: rawDocumentBatch.length }, rawDocumentBatch, rawTicker);
            });
        }
        return new internal_1.SecurityToken({ ticker }, context);
    });
}
exports.prepareSetTokenDocuments = prepareSetTokenDocuments;
/**
 * @hidden
 */
function getAuthorization({ ticker, documents }) {
    const { storage: { currentDocIds }, } = this;
    const transactions = [];
    if (documents.length) {
        transactions.push(types_1.TxTags.asset.AddDocuments);
    }
    if (currentDocIds.length) {
        transactions.push(types_1.TxTags.asset.RemoveDocuments);
    }
    return {
        permissions: {
            tokens: [new internal_1.SecurityToken({ ticker }, this.context)],
            transactions,
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
function prepareStorage({ ticker }) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { query }, }, context, } = this;
        const currentDocEntries = yield query.asset.assetDocuments.entries(conversion_1.stringToTicker(ticker, context));
        const currentDocIds = [];
        const currentDocs = [];
        currentDocEntries.forEach(([key, doc]) => {
            const [, id] = key.args;
            currentDocIds.push(id);
            currentDocs.push(conversion_1.documentToTokenDocument(doc));
        });
        return {
            currentDocIds,
            currentDocs,
        };
    });
}
exports.prepareStorage = prepareStorage;
/**
 * @hidden
 */
const setTokenDocuments = () => new internal_1.Procedure(prepareSetTokenDocuments, getAuthorization, prepareStorage);
exports.setTokenDocuments = setTokenDocuments;
//# sourceMappingURL=setTokenDocuments.js.map