"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 Asset'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.asset = new internal_1.Asset({ ticker }, context);
    }
    /**
     * @hidden
     * Check if a value is of type {@link UniqueIdentifiers}
     */
    static isUniqueIdentifiers(identifier) {
        const { id, ticker } = identifier;
        return id instanceof bignumber_js_1.default && typeof ticker === 'string';
    }
    /**
     * Retrieve the Asset's total supply at this checkpoint
     */
    totalSupply() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, asset: { ticker }, id, } = this;
            const rawSupply = yield context.polymeshApi.query.checkpoint.totalSupply((0, conversion_1.stringToTicker)(ticker, context), (0, conversion_1.bigNumberToU64)(id, context));
            return (0, conversion_1.balanceToBigNumber)(rawSupply);
        });
    }
    /**
     * Retrieve this Checkpoint's creation date
     */
    createdAt() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, asset: { ticker }, id, } = this;
            const creationTime = yield context.polymeshApi.query.checkpoint.timestamps((0, conversion_1.stringToTicker)(ticker, context), (0, conversion_1.bigNumberToU64)(id, context));
            return (0, conversion_1.momentToDate)(creationTime);
        });
    }
    /**
     * Retrieve all Asset Holder balances at this Checkpoint
     *
     * @note supports pagination
     */
    allBalances(paginationOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query: { checkpoint, asset }, }, }, context, asset: { ticker }, id, } = this;
            const rawTicker = (0, conversion_1.stringToTicker)(ticker, context);
            const { entries, lastKey: next } = yield (0, internal_2.requestPaginated)(asset.balanceOf, {
                arg: rawTicker,
                paginationOpts,
            });
            const currentDidBalances = [];
            const balanceUpdatesMultiParams = [];
            entries.forEach(([storageKey, balance]) => {
                const { args: [, identityId], } = storageKey;
                currentDidBalances.push({
                    did: (0, conversion_1.identityIdToString)(identityId),
                    balance: (0, conversion_1.balanceToBigNumber)(balance),
                });
                balanceUpdatesMultiParams.push((0, utils_1.tuple)(rawTicker, identityId));
            });
            const rawBalanceUpdates = yield checkpoint.balanceUpdates.multi(balanceUpdatesMultiParams);
            const checkpointBalanceMultiParams = [];
            const signingIdentityBalances = [];
            rawBalanceUpdates.forEach((rawCheckpointIds, index) => {
                const firstUpdatedCheckpoint = rawCheckpointIds.find(checkpointId => (0, conversion_1.u64ToBigNumber)(checkpointId).gte(id));
                const { did, balance } = currentDidBalances[index];
                if (firstUpdatedCheckpoint) {
                    checkpointBalanceMultiParams.push({
                        did,
                        params: (0, utils_1.tuple)([rawTicker, firstUpdatedCheckpoint], (0, conversion_1.stringToIdentityId)(did, context)),
                    });
                }
                else {
                    signingIdentityBalances.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: (0, conversion_1.balanceToBigNumber)(checkpointBalances[index]),
                    })),
                    ...signingIdentityBalances,
                ],
                next,
            };
        });
    }
    /**
     * Retrieve the balance of a specific Asset Holder Identity at this Checkpoint
     *
     * @param args.identity - defaults to the signing Identity
     */
    balance(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, context: { polymeshApi: { query: { checkpoint }, }, }, asset: { ticker }, id, } = this;
            const identity = yield (0, internal_2.getIdentity)(args === null || args === void 0 ? void 0 : args.identity, context);
            const rawTicker = (0, conversion_1.stringToTicker)(ticker, context);
            const rawIdentityId = (0, conversion_1.stringToIdentityId)(identity.did, context);
            const balanceUpdates = yield checkpoint.balanceUpdates(rawTicker, rawIdentityId);
            const firstUpdatedCheckpoint = balanceUpdates.find(checkpointId => (0, conversion_1.u64ToBigNumber)(checkpointId).gte(id));
            let balance;
            if (firstUpdatedCheckpoint) {
                const rawBalance = yield checkpoint.balance((0, utils_1.tuple)(rawTicker, firstUpdatedCheckpoint), rawIdentityId);
                balance = (0, conversion_1.balanceToBigNumber)(rawBalance);
            }
            else {
                balance = yield identity.getAssetBalance({ 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, asset: { ticker }, id, } = this;
            const rawCheckpointId = yield checkpoint.checkpointIdSequence((0, conversion_1.stringToTicker)(ticker, context));
            return id.lte((0, conversion_1.u64ToBigNumber)(rawCheckpointId));
        });
    }
    /**
     * Return the Checkpoint's ticker and identifier
     */
    toJson() {
        const { asset, id } = this;
        return (0, internal_2.toHumanReadable)({
            ticker: asset,
            id,
        });
    }
}
exports.Checkpoint = Checkpoint;
//# sourceMappingURL=Checkpoint.js.map