"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.Portfolios = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const internal_1 = require("../../../internal");
const types_1 = require("../../../types");
const conversion_1 = require("../../../utils/conversion");
const internal_2 = require("../../../utils/internal");
/**
 * Handles all Portfolio related functionality on the Identity side
 */
class Portfolios extends internal_1.Namespace {
    /**
     * @hidden
     */
    constructor(parent, context) {
        super(parent, context);
        const { did } = parent;
        this.create = internal_2.createProcedureMethod({ getProcedureAndArgs: args => [internal_1.createPortfolio, args] }, context);
        this.delete = internal_2.createProcedureMethod({
            getProcedureAndArgs: args => {
                const { portfolio } = args;
                const id = portfolio instanceof bignumber_js_1.default ? portfolio : portfolio.id;
                return [internal_1.deletePortfolio, { id, did }];
            },
        }, context);
    }
    /**
     * Retrieve all the Portfolios owned by this Identity
     */
    getPortfolios() {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, context: { polymeshApi: { query: { portfolio }, }, }, parent: { did }, } = this;
            const identityId = conversion_1.stringToIdentityId(did, context);
            const rawPortfolios = yield portfolio.portfolios.entries(identityId);
            const portfolios = [
                new internal_1.DefaultPortfolio({ did }, context),
            ];
            rawPortfolios.forEach(([key]) => {
                portfolios.push(new internal_1.NumberedPortfolio({ id: conversion_1.u64ToBigNumber(key.args[1]), did }, context));
            });
            return portfolios;
        });
    }
    /**
     * Retrieve all Portfolios custodied by this Identity.
     *   This only includes portfolios owned by a different Identity but custodied by this one.
     *   To fetch Portfolios owned by this Identity, use [[getPortfolios]]
     *
     * @note supports pagination
     */
    getCustodiedPortfolios(paginationOpts) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, context: { polymeshApi: { query: { portfolio }, }, }, parent: { did: custodianDid }, } = this;
            const custodian = conversion_1.stringToIdentityId(custodianDid, context);
            const { entries: portfolioEntries, lastKey: next } = yield internal_2.requestPaginated(portfolio.portfoliosInCustody, {
                arg: custodian,
                paginationOpts,
            });
            const data = portfolioEntries.map(([{ args }]) => {
                const { did: ownerDid, kind } = args[1];
                const did = conversion_1.identityIdToString(ownerDid);
                if (kind.isDefault) {
                    return new internal_1.DefaultPortfolio({ did }, context);
                }
                const id = conversion_1.u64ToBigNumber(kind.asUser);
                return new internal_1.NumberedPortfolio({ did, id }, context);
            });
            return {
                data,
                next,
            };
        });
    }
    // eslint-disable-next-line require-jsdoc
    getPortfolio(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, parent: { did }, } = this;
            const portfolioId = args === null || args === void 0 ? void 0 : args.portfolioId;
            if (!portfolioId) {
                return new internal_1.DefaultPortfolio({ did }, context);
            }
            const numberedPortfolio = new internal_1.NumberedPortfolio({ id: portfolioId, did }, context);
            const exists = yield numberedPortfolio.exists();
            if (!exists) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.ValidationError,
                    message: "The Portfolio doesn't exist",
                });
            }
            return numberedPortfolio;
        });
    }
}
exports.Portfolios = Portfolios;
//# sourceMappingURL=Portfolios.js.map