"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.inviteExternalAgent = exports.prepareStorage = exports.getAuthorization = exports.prepareInviteExternalAgent = void 0;
const types_1 = require("../../polkadot/types");
const internal_1 = require("../../internal");
const types_2 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
const authorizationDataResolver = (value, context) => conversion_1.authorizationToAuthorizationData({
    type: types_2.AuthorizationType.BecomeAgent,
    value,
}, context);
/**
 * @hidden
 */
function prepareInviteExternalAgent(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx: { identity }, }, }, context, storage: { token }, } = this;
        const { ticker, target, permissions, expiry } = args;
        const [currentAgents, did] = yield Promise.all([
            token.permissions.getAgents(),
            internal_2.getDid(target, context),
        ]);
        const isAgent = !!currentAgents.find(({ agent: { did: agentDid } }) => agentDid === did);
        if (isAgent) {
            throw new internal_1.PolymeshError({
                code: types_2.ErrorCode.NoDataChange,
                message: 'The target Identity is already an External Agent',
            });
        }
        const rawSignatory = conversion_1.signerValueToSignatory({ type: types_2.SignerType.Identity, value: conversion_1.signerToString(target) }, context);
        let rawAuthorizationData;
        if (permissions instanceof internal_1.KnownPermissionGroup || permissions instanceof internal_1.CustomPermissionGroup) {
            rawAuthorizationData = authorizationDataResolver(permissions, context);
        }
        else {
            // We know this procedure returns a PostTransactionValue, so this assertion is necessary
            const createGroupResult = (yield this.addProcedure(internal_1.createGroup(), {
                ticker,
                permissions,
            }));
            rawAuthorizationData = createGroupResult.transform(customPermissionGroup => authorizationDataResolver(customPermissionGroup, context));
        }
        const rawExpiry = internal_2.optionize(conversion_1.dateToMoment)(expiry, context);
        this.addTransaction(identity.addAuthorization, {}, rawSignatory, rawAuthorizationData, rawExpiry);
    });
}
exports.prepareInviteExternalAgent = prepareInviteExternalAgent;
/**
 * @hidden
 */
function getAuthorization() {
    const { storage: { token }, } = this;
    return {
        permissions: {
            transactions: [types_1.TxTags.identity.AddAuthorization],
            tokens: [token],
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
function prepareStorage({ ticker }) {
    const { context } = this;
    return {
        token: new internal_1.SecurityToken({ ticker }, context),
    };
}
exports.prepareStorage = prepareStorage;
/**
 * @hidden
 */
const inviteExternalAgent = () => new internal_1.Procedure(prepareInviteExternalAgent, getAuthorization, prepareStorage);
exports.inviteExternalAgent = inviteExternalAgent;
//# sourceMappingURL=inviteExternalAgent.js.map