"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.Checkpoint = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const internal_1 = require("../../internal");
const utils_1 = require("../../types/utils");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * Represents a snapshot of the Security Token's holders and their respective balances
 *   at a certain point in time
 */
class Checkpoint extends internal_1.Entity {
    /**
     * @hidden
     */
    constructor(identifiers, context) {
        super(identifiers, context);
        const { id, ticker } = identifiers;
        this.id = id;
        this.token = new internal_1.SecurityToken({ ticker }, context);
    }
    /**
     * @hidden
     * Check if a value is of type [[UniqueIdentifiers]]
     */
    static isUniqueIdentifiers(identifier) {
        const { id, ticker } = identifier;
        return id instanceof bignumber_js_1.default && typeof ticker === 'string';
    }
    /**
     * Retrieve the Security Token's total supply at this checkpoint
     */
    totalSupply() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, token: { ticker }, id, } = this;
            const rawSupply = yield context.polymeshApi.query.checkpoint.totalSupply(conversion_1.stringToTicker(ticker, context), conversion_1.numberToU64(id, context));
            return conversion_1.balanceToBigNumber(rawSupply);
        });
    }
    /**
     * Retrieve this Checkpoint's creation date
     */
    createdAt() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, token: { ticker }, id, } = this;
            const creationTime = yield context.polymeshApi.query.checkpoint.timestamps(conversion_1.stringToTicker(ticker, context), conversion_1.numberToU64(id, context));
            return conversion_1.momentToDate(creationTime);
        });
    }
    /**
     * Retrieve all Tokenholder balances at this Checkpoint
     *
     * @note supports pagination
     */
    allBalances(paginationOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query: { checkpoint, asset }, }, }, context, token: { ticker }, id, } = this;
            const rawTicker = conversion_1.stringToTicker(ticker, context);
            const { entries, lastKey: next } = yield internal_2.requestPaginated(asset.balanceOf, {
                arg: rawTicker,
                paginationOpts,
            });
            const currentDidBalances = [];
            const balanceUpdatesMultiParams = [];
            entries.forEach(([storageKey, balance]) => {
                const { args: [, identityId], } = storageKey;
                currentDidBalances.push({
                    did: conversion_1.identityIdToString(identityId),
                    balance: conversion_1.balanceToBigNumber(balance),
                });
                balanceUpdatesMultiParams.push(utils_1.tuple(rawTicker, identityId));
            });
            const rawBalanceUpdates = yield checkpoint.balanceUpdates.multi(balanceUpdatesMultiParams);
            const checkpointBalanceMultiParams = [];
            const currentIdentityBalances = [];
            rawBalanceUpdates.forEach((rawCheckpointIds, index) => {
                const firstUpdatedCheckpoint = rawCheckpointIds.find(checkpointId => conversion_1.u64ToBigNumber(checkpointId).gte(id));
                const { did, balance } = currentDidBalances[index];
                if (firstUpdatedCheckpoint) {
                    checkpointBalanceMultiParams.push({
                        did,
                        params: utils_1.tuple([rawTicker, firstUpdatedCheckpoint], conversion_1.stringToIdentityId(did, context)),
                    });
                }
                else {
                    currentIdentityBalances.push({
                        identity: new internal_1.Identity({ did }, context),
                        balance,
                    });
                }
            });
            const checkpointBalances = yield checkpoint.balance.multi(checkpointBalanceMultiParams.map(({ params }) => params));
            return {
                data: [
                    ...checkpointBalanceMultiParams.map(({ did }, index) => ({
                        identity: new internal_1.Identity({ did }, context),
                        balance: conversion_1.balanceToBigNumber(checkpointBalances[index]),
                    })),
                    ...currentIdentityBalances,
                ],
                next,
            };
        });
    }
    /**
     * Retrieve the balance of a specific Tokenholder Identity at this Checkpoint
     *
     * @param args.identity - defaults to the current Identity
     */
    balance(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, context: { polymeshApi: { query: { checkpoint }, }, }, token: { ticker }, id, } = this;
            const did = yield internal_2.getDid(args === null || args === void 0 ? void 0 : args.identity, context);
            const identity = new internal_1.Identity({ did }, context);
            const rawTicker = conversion_1.stringToTicker(ticker, context);
            const rawIdentityId = conversion_1.stringToIdentityId(did, context);
            const balanceUpdates = yield checkpoint.balanceUpdates(rawTicker, rawIdentityId);
            const firstUpdatedCheckpoint = balanceUpdates.find(checkpointId => conversion_1.u64ToBigNumber(checkpointId).gte(id));
            let balance;
            if (firstUpdatedCheckpoint) {
                const rawBalance = yield checkpoint.balance(utils_1.tuple(rawTicker, firstUpdatedCheckpoint), rawIdentityId);
                balance = conversion_1.balanceToBigNumber(rawBalance);
            }
            else {
                balance = yield identity.getTokenBalance({ ticker });
            }
            return balance;
        });
    }
    /**
     * Determine whether this Checkpoint exists on chain
     */
    exists() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query: { checkpoint }, }, }, context, token: { ticker }, id, } = this;
            const rawCheckpointId = yield checkpoint.checkpointIdSequence(conversion_1.stringToTicker(ticker, context));
            return id.lte(conversion_1.u64ToBigNumber(rawCheckpointId));
        });
    }
    /**
     * Return the Checkpoint's ticker and identifier
     */
    toJson() {
        const { token, id } = this;
        return internal_2.toHumanReadable({
            ticker: token,
            id,
        });
    }
}
exports.Checkpoint = Checkpoint;
//# sourceMappingURL=Checkpoint.js.map