"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.createGroup = exports.prepareStorage = exports.getAuthorization = exports.prepareCreateGroup = exports.createCreateGroupResolver = void 0;
const bluebird_1 = __importDefault(require("bluebird"));
const lodash_1 = require("lodash");
const internal_1 = require("../../internal");
const types_1 = require("../../types");
const conversion_1 = require("../../utils/conversion");
const internal_2 = require("../../utils/internal");
/**
 * @hidden
 */
const createCreateGroupResolver = (context) => (receipt) => {
    const [{ data }] = internal_2.filterEventRecords(receipt, 'externalAgents', 'GroupCreated');
    return new internal_1.CustomPermissionGroup({ id: conversion_1.u64ToBigNumber(data[2]), ticker: conversion_1.tickerToString(data[1]) }, context);
};
exports.createCreateGroupResolver = createCreateGroupResolver;
/**
 * @hidden
 */
function prepareCreateGroup(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx: { externalAgents }, }, }, context, storage: { asset }, } = this;
        const { ticker, permissions } = args;
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const { transactions } = conversion_1.permissionsLikeToPermissions(permissions, context);
        const { custom, known } = yield asset.permissions.getGroups();
        const allGroups = [...custom, ...known];
        const currentGroupPermissions = yield bluebird_1.default.map(allGroups, group => group.getPermissions());
        const duplicatedGroupIndex = currentGroupPermissions.findIndex(({ transactions: transactionPermissions }) => lodash_1.isEqual(transactionPermissions, transactions));
        if (duplicatedGroupIndex > -1) {
            const group = allGroups[duplicatedGroupIndex];
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.NoDataChange,
                message: 'There already exists a group with the exact same permissions',
                data: { groupId: group instanceof internal_1.CustomPermissionGroup ? group.id : group.type },
            });
        }
        const rawExtrinsicPermissions = conversion_1.transactionPermissionsToExtrinsicPermissions(transactions, context);
        const [customPermissionGroup] = this.addTransaction({
            transaction: externalAgents.createGroup,
            resolvers: [exports.createCreateGroupResolver(context)],
            args: [rawTicker, rawExtrinsicPermissions],
        });
        return customPermissionGroup;
    });
}
exports.prepareCreateGroup = prepareCreateGroup;
/**
 * @hidden
 */
function getAuthorization() {
    const { storage: { asset }, } = this;
    return {
        permissions: {
            transactions: [types_1.TxTags.externalAgents.CreateGroup],
            assets: [asset],
            portfolios: [],
        },
    };
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
function prepareStorage({ ticker }) {
    const { context } = this;
    return {
        asset: new internal_1.Asset({ ticker }, context),
    };
}
exports.prepareStorage = prepareStorage;
/**
 * @hidden
 */
const createGroup = () => new internal_1.Procedure(prepareCreateGroup, getAuthorization, prepareStorage);
exports.createGroup = createGroup;
//# sourceMappingURL=createGroup.js.map