"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());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addTransferRestriction = exports.getAuthorization = exports.prepareAddTransferRestriction = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const bluebird_1 = __importDefault(require("bluebird"));
const lodash_1 = require("lodash");
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
function prepareAddTransferRestriction(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx: { statistics }, query, consts, }, }, context, } = this;
        const { ticker, exemptedScopeIds = [], exemptedIdentities = [] } = args;
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const maxTransferManagers = conversion_1.u32ToBigNumber(consts.statistics.maxTransferManagersPerAsset);
        const currentTms = yield query.statistics.activeTransferManagers(ticker);
        const restrictionAmount = new bignumber_js_1.default(currentTms.length);
        if (restrictionAmount.gte(maxTransferManagers)) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.LimitExceeded,
                message: 'Transfer Restriction limit reached',
                data: { limit: maxTransferManagers },
            });
        }
        let value;
        if (args.type === types_1.TransferRestrictionType.Count) {
            value = args.count;
        }
        else {
            value = args.percentage;
        }
        const exists = !!currentTms.find(transferManager => {
            const restriction = conversion_1.transferManagerToTransferRestriction(transferManager);
            return restriction.type === args.type && restriction.value.eq(value);
        });
        if (exists) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.NoDataChange,
                message: 'Cannot add the same restriction more than once',
            });
        }
        const rawTransferManager = conversion_1.transferRestrictionToTransferManager({ type: args.type, value }, context);
        const transactions = [
            internal_2.checkTxType({
                transaction: statistics.addTransferManager,
                args: [rawTicker, rawTransferManager],
            }),
        ];
        const identityScopes = yield bluebird_1.default.map(exemptedIdentities, identityValue => {
            let identity;
            if (typeof identityValue === 'string') {
                identity = new internal_1.Identity({ did: identityValue }, context);
            }
            else {
                identity = identityValue;
            }
            return identity.getScopeId({ asset: ticker });
        });
        const exempted = [...exemptedScopeIds, ...identityScopes];
        const exemptedLength = exempted.length;
        if (exemptedLength) {
            const hasDuplicates = lodash_1.uniq(exempted).length !== exemptedLength;
            if (hasDuplicates) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.ValidationError,
                    message: 'One or more of the passed exempted Scope IDs/Identities are repeated',
                });
            }
            const scopeIds = exempted.map(scopeId => conversion_1.stringToScopeId(scopeId, context));
            transactions.push(internal_2.checkTxType({
                transaction: statistics.addExemptedEntities,
                feeMultiplier: new bignumber_js_1.default(scopeIds.length),
                args: [rawTicker, rawTransferManager, scopeIds],
            }));
        }
        this.addBatchTransaction({ transactions });
        return restrictionAmount.plus(1);
    });
}
exports.prepareAddTransferRestriction = prepareAddTransferRestriction;
/**
 * @hidden
 */
function getAuthorization({ ticker, exemptedScopeIds = [], exemptedIdentities = [] }) {
    const transactions = [types_1.TxTags.statistics.AddTransferManager];
    const exempted = [...exemptedScopeIds, ...exemptedIdentities];
    if (exempted.length) {
        transactions.push(types_1.TxTags.statistics.AddExemptedEntities);
    }
    return {
        permissions: {
            assets: [new internal_1.Asset({ ticker }, this.context)],
            transactions,
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const addTransferRestriction = () => new internal_1.Procedure(prepareAddTransferRestriction, getAuthorization);
exports.addTransferRestriction = addTransferRestriction;
//# sourceMappingURL=addTransferRestriction.js.map