"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.modifyCaDefaultConfig = exports.getAuthorization = exports.prepareModifyCaDefaultConfig = void 0;
const utils_1 = require("./utils");
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const utils_2 = require("../../types/utils");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
const areSameTargets = (targets, newTargets) => {
    const { identities: newIdentities, treatment: newTreatment } = newTargets;
    const { identities, treatment } = targets;
    return (internal_2.hasSameElements(identities, newIdentities, (identity, newIdentity) => conversion_1.signerToString(identity) === conversion_1.signerToString(newIdentity)) && treatment === newTreatment);
};
/**
 * @hidden
 */
function prepareModifyCaDefaultConfig(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { ticker, targets: newTargets, defaultTaxWithholding: newDefaultTaxWithholding, taxWithholdings: newTaxWithholdings, } = args;
        const noArguments = newTargets === undefined &&
            newDefaultTaxWithholding === undefined &&
            newTaxWithholdings === undefined;
        if (noArguments) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.NoDataChange,
                message: 'Nothing to modify',
            });
        }
        if (newTargets) {
            utils_1.assertCaTargetsValid(newTargets, context);
        }
        if (newTaxWithholdings) {
            utils_1.assertCaTaxWithholdingsValid(newTaxWithholdings, context);
        }
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const securityToken = new internal_1.SecurityToken({ ticker }, context);
        const { targets, defaultTaxWithholding, taxWithholdings, } = yield securityToken.corporateActions.getDefaultConfig();
        if (newTargets) {
            if (areSameTargets(targets, newTargets)) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.NoDataChange,
                    message: 'New targets are the same as the current ones',
                });
            }
            this.addTransaction(tx.corporateAction.setDefaultTargets, {}, rawTicker, conversion_1.targetsToTargetIdentities(newTargets, context));
        }
        if (newDefaultTaxWithholding) {
            if (newDefaultTaxWithholding.eq(defaultTaxWithholding)) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.NoDataChange,
                    message: 'New default tax withholding is the same as the current one',
                });
            }
            this.addTransaction(tx.corporateAction.setDefaultWithholdingTax, {}, rawTicker, conversion_1.percentageToPermill(newDefaultTaxWithholding, context));
        }
        if (newTaxWithholdings) {
            const areSameWithholdings = internal_2.hasSameElements(taxWithholdings, newTaxWithholdings, ({ identity, percentage }, { identity: newIdentity, percentage: newPercentage }) => conversion_1.signerToString(identity) === conversion_1.signerToString(newIdentity) && percentage.eq(newPercentage));
            if (areSameWithholdings) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.NoDataChange,
                    message: 'New per-Identity tax withholding percentages are the same as current ones',
                });
            }
            const batchParams = newTaxWithholdings.map(({ identity, percentage }) => utils_2.tuple(rawTicker, conversion_1.stringToIdentityId(conversion_1.signerToString(identity), context), conversion_1.percentageToPermill(percentage, context)));
            this.addBatchTransaction(tx.corporateAction.setDidWithholdingTax, {}, batchParams);
        }
    });
}
exports.prepareModifyCaDefaultConfig = prepareModifyCaDefaultConfig;
/**
 * @hidden
 */
function getAuthorization({ ticker, targets, defaultTaxWithholding, taxWithholdings }) {
    const transactions = [];
    if (targets) {
        transactions.push(types_1.TxTags.corporateAction.SetDefaultTargets);
    }
    if (defaultTaxWithholding) {
        transactions.push(types_1.TxTags.corporateAction.SetDefaultWithholdingTax);
    }
    if (taxWithholdings) {
        transactions.push(types_1.TxTags.corporateAction.SetDidWithholdingTax);
    }
    return {
        permissions: {
            transactions,
            portfolios: [],
            tokens: [new internal_1.SecurityToken({ ticker }, this.context)],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const modifyCaDefaultConfig = () => new internal_1.Procedure(prepareModifyCaDefaultConfig, getAuthorization);
exports.modifyCaDefaultConfig = modifyCaDefaultConfig;
//# sourceMappingURL=modifyCaDefaultConfig.js.map