"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.createPortfolio = exports.prepareCreatePortfolio = exports.createPortfolioResolver = void 0;
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
const createPortfolioResolver = (context) => (receipt) => {
    const [{ data }] = internal_2.filterEventRecords(receipt, 'portfolio', 'PortfolioCreated');
    const did = conversion_1.identityIdToString(data[0]);
    const id = conversion_1.u64ToBigNumber(data[1]);
    return new internal_1.NumberedPortfolio({ did, id }, context);
};
exports.createPortfolioResolver = createPortfolioResolver;
/**
 * @hidden
 */
function prepareCreatePortfolio(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { name: portfolioName } = args;
        const { did } = yield context.getSigningIdentity();
        const rawIdentityId = conversion_1.stringToIdentityId(did, context);
        const rawName = conversion_1.stringToText(portfolioName, context);
        const existingPortfolioNumber = yield internal_2.getPortfolioIdByName(rawIdentityId, rawName, context);
        if (existingPortfolioNumber) {
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: 'A Portfolio with that name already exists',
            });
        }
        const [newNumberedPortfolio] = this.addTransaction({
            transaction: tx.portfolio.createPortfolio,
            resolvers: [exports.createPortfolioResolver(context)],
            args: [rawName],
        });
        return newNumberedPortfolio;
    });
}
exports.prepareCreatePortfolio = prepareCreatePortfolio;
/**
 * @hidden
 */
const createPortfolio = () => new internal_1.Procedure(prepareCreatePortfolio, {
    permissions: {
        transactions: [types_1.TxTags.portfolio.CreatePortfolio],
        assets: [],
        portfolios: [],
    },
});
exports.createPortfolio = createPortfolio;
//# sourceMappingURL=createPortfolio.js.map