"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.reserveTicker = exports.getAuthorization = exports.prepareReserveTicker = exports.createTickerReservationResolver = 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
 * NOTE: this might seem redundant but it's done in case some mutation is done on the ticker on chain (e.g. upper case or truncating)
 */
const createTickerReservationResolver = (context) => (receipt) => {
    const [{ data }] = internal_2.filterEventRecords(receipt, 'asset', 'TickerRegistered');
    const newTicker = conversion_1.tickerToString(data[1]);
    return new internal_1.TickerReservation({ ticker: newTicker }, context);
};
exports.createTickerReservationResolver = createTickerReservationResolver;
/**
 * @hidden
 */
function prepareReserveTicker(args) {
    return __awaiter(this, void 0, void 0, function* () {
        const { context: { polymeshApi: { tx }, }, context, } = this;
        const { ticker, extendPeriod = false } = args;
        const rawTicker = conversion_1.stringToTicker(ticker, context);
        const reservation = new internal_1.TickerReservation({ ticker }, context);
        const { expiryDate, status } = yield reservation.details();
        if (status === types_2.TickerReservationStatus.AssetCreated) {
            throw new internal_1.PolymeshError({
                code: types_2.ErrorCode.UnmetPrerequisite,
                message: `An Asset with ticker "${ticker}" already exists`,
            });
        }
        else if (status === types_2.TickerReservationStatus.Reserved) {
            if (!extendPeriod) {
                throw new internal_1.PolymeshError({
                    code: types_2.ErrorCode.UnmetPrerequisite,
                    message: `Ticker "${ticker}" already reserved`,
                    data: {
                        expiryDate,
                    },
                });
            }
        }
        else {
            if (extendPeriod) {
                throw new internal_1.PolymeshError({
                    code: types_2.ErrorCode.UnmetPrerequisite,
                    message: 'Ticker not reserved or the reservation has expired',
                });
            }
        }
        const [newReservation] = this.addTransaction({
            transaction: tx.asset.registerTicker,
            resolvers: [exports.createTickerReservationResolver(context)],
            args: [rawTicker],
        });
        return newReservation;
    });
}
exports.prepareReserveTicker = prepareReserveTicker;
/**
 * @hidden
 * If extending a reservation, the user must be the ticker owner
 */
function getAuthorization({ ticker, extendPeriod, }) {
    const auth = {
        permissions: {
            transactions: [types_1.TxTags.asset.RegisterTicker],
            assets: [],
            portfolios: [],
        },
    };
    if (extendPeriod) {
        return Object.assign(Object.assign({}, auth), { roles: [{ type: types_2.RoleType.TickerOwner, ticker }] });
    }
    return auth;
}
exports.getAuthorization = getAuthorization;
/**
 * @hidden
 */
const reserveTicker = () => new internal_1.Procedure(prepareReserveTicker, getAuthorization);
exports.reserveTicker = reserveTicker;
//# sourceMappingURL=reserveTicker.js.map