"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.initiateCorporateAction = exports.getAuthorization = exports.prepareInitiateCorporateAction = exports.createCaIdResolver = 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");
/**
 * @hidden
 */
const createCaIdResolver = () => (receipt) => {
    const [{ data }] = internal_2.filterEventRecords(receipt, 'corporateAction', 'CAInitiated');
    return data[1];
};
exports.createCaIdResolver = createCaIdResolver;
/**
 * @hidden
 */
function prepareInitiateCorporateAction(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx, query }, }, context, } = this;
        const { ticker, kind, declarationDate = new Date(), checkpoint = null, description, targets = null, defaultTaxWithholding = null, taxWithholdings = null, } = args;
        if (targets) {
            utils_1.assertCaTargetsValid(targets, context);
        }
        if (taxWithholdings) {
            utils_1.assertCaTaxWithholdingsValid(taxWithholdings, context);
        }
        if (declarationDate > new Date()) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.ValidationError,
                message: 'Declaration date must be in the past',
            });
        }
        const rawMaxDetailsLength = yield query.corporateAction.maxDetailsLength();
        const maxDetailsLength = conversion_1.u32ToBigNumber(rawMaxDetailsLength);
        if (maxDetailsLength.lt(description.length)) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.ValidationError,
                message: 'Description too long',
                data: {
                    maxLength: maxDetailsLength.toNumber(),
                },
            });
        }
        let checkpointValue;
        if (checkpoint) {
            checkpointValue = yield internal_2.getCheckpointValue(checkpoint, ticker, context);
            yield utils_1.assertCaCheckpointValid(checkpointValue);
        }
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const rawKind = conversion_1.corporateActionKindToCaKind(kind, context);
        const rawDeclDate = conversion_1.dateToMoment(declarationDate, context);
        const rawRecordDate = internal_2.optionize(conversion_1.checkpointToRecordDateSpec)(checkpointValue, context);
        const rawDetails = conversion_1.stringToText(description, context);
        const rawTargets = internal_2.optionize(conversion_1.targetsToTargetIdentities)(targets, context);
        const rawTax = internal_2.optionize(conversion_1.percentageToPermill)(defaultTaxWithholding, context);
        const rawWithholdings = taxWithholdings &&
            taxWithholdings.map(({ identity, percentage }) => utils_2.tuple(conversion_1.stringToIdentityId(conversion_1.signerToString(identity), context), conversion_1.percentageToPermill(percentage, context)));
        const [caId] = this.addTransaction({
            transaction: tx.corporateAction.initiateCorporateAction,
            resolvers: [exports.createCaIdResolver()],
            args: [
                rawTicker,
                rawKind,
                rawDeclDate,
                rawRecordDate,
                rawDetails,
                rawTargets,
                rawTax,
                rawWithholdings,
            ],
        });
        return caId;
    });
}
exports.prepareInitiateCorporateAction = prepareInitiateCorporateAction;
/**
 * @hidden
 */
function getAuthorization({ ticker }) {
    return {
        permissions: {
            transactions: [types_1.TxTags.corporateAction.InitiateCorporateAction],
            assets: [new internal_1.Asset({ ticker }, this.context)],
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const initiateCorporateAction = () => new internal_1.Procedure(prepareInitiateCorporateAction, getAuthorization);
exports.initiateCorporateAction = initiateCorporateAction;
//# sourceMappingURL=initiateCorporateAction.js.map