"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.payDividends = exports.getAuthorization = exports.preparePayDividends = 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
 */
function preparePayDividends(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx, query: { capitalDistribution }, }, }, context, } = this;
        const { distribution: { targets: { identities, treatment }, id: localId, asset: { ticker }, paymentDate, expiryDate, }, targets, } = args;
        utils_1.assertDistributionOpen(paymentDate, expiryDate);
        const excluded = [];
        targets.forEach(target => {
            const targetDid = conversion_1.signerToString(target);
            const found = !!identities.find(({ did }) => did === targetDid);
            if (internal_2.xor(found, treatment === types_1.TargetTreatment.Include)) {
                excluded.push(new internal_1.Identity({ did: targetDid }, context));
            }
        });
        if (excluded.length) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'Some of the supplied Identities are not included in this Distribution',
                data: { excluded },
            });
        }
        const rawCaId = conversion_1.corporateActionIdentifierToCaId({ ticker, localId }, context);
        const rawArgs = targets.map(target => utils_2.tuple(rawCaId, conversion_1.stringToIdentityId(conversion_1.signerToString(target), context)));
        const holderPaidList = yield capitalDistribution.holderPaid.multi(rawArgs);
        const alreadyClaimedList = [];
        holderPaidList.forEach((holderPaid, i) => {
            if (conversion_1.boolToBoolean(holderPaid)) {
                alreadyClaimedList.push(new internal_1.Identity({ did: conversion_1.signerToString(targets[i]) }, context));
            }
        });
        if (alreadyClaimedList.length) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'Some of the supplied Identities have already either been paid or claimed their share of the Distribution',
                data: {
                    targets: alreadyClaimedList,
                },
            });
        }
        const transaction = tx.capitalDistribution.pushBenefit;
        this.addBatchTransaction({
            transactions: rawArgs.map(txArgs => ({
                transaction,
                args: txArgs,
            })),
        });
    });
}
exports.preparePayDividends = preparePayDividends;
/**
 * @hidden
 */
function getAuthorization() {
    return __awaiter(this, void 0, void 0, function* () {
        return {
            permissions: {
                transactions: [types_1.TxTags.capitalDistribution.PushBenefit],
                assets: [],
                portfolios: [],
            },
        };
    });
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const payDividends = () => new internal_1.Procedure(preparePayDividends, getAuthorization);
exports.payDividends = payDividends;
//# sourceMappingURL=payDividends.js.map