"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.TickerReservation = void 0;
const internal_1 = require("../../../internal");
const conversion_1 = require("../../../utils/conversion");
const internal_2 = require("../../../utils/internal");
const types_1 = require("./types");
/**
 * Represents a reserved Asset symbol in the Polymesh blockchain. Ticker reservations expire
 *   after a set length of time, after which they can be reserved by another Identity.
 *   A Ticker must be previously reserved by an Identity for that Identity to be able create an Asset with it
 */
class TickerReservation extends internal_1.Entity {
    /**
     * @hidden
     */
    constructor(identifiers, context) {
        super(identifiers, context);
        const { ticker } = identifiers;
        this.ticker = ticker;
        this.extend = internal_2.createProcedureMethod({
            getProcedureAndArgs: () => [internal_1.reserveTicker, { ticker, extendPeriod: true }],
            voidArgs: true,
        }, context);
        this.createAsset = internal_2.createProcedureMethod({
            getProcedureAndArgs: args => [internal_1.createAsset, Object.assign(Object.assign({}, args), { ticker, reservationRequired: true })],
        }, context);
        this.transferOwnership = internal_2.createProcedureMethod({ getProcedureAndArgs: args => [internal_1.transferTickerOwnership, Object.assign({ ticker }, args)] }, context);
    }
    /**
     * @hidden
     * Check if a value is of type [[UniqueIdentifiers]]
     */
    static isUniqueIdentifiers(identifier) {
        const { ticker } = identifier;
        return typeof ticker === 'string';
    }
    // eslint-disable-next-line require-jsdoc
    details(callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query: { asset }, queryMulti, }, }, ticker, context, } = this;
            const rawTicker = conversion_1.stringToTicker(ticker, context);
            const assembleResult = ({ owner: tickerOwner, expiry }, { owner_did: assetOwner }) => {
                const tickerOwned = !tickerOwner.isEmpty;
                const assetOwned = !assetOwner.isEmpty;
                let status;
                let expiryDate = null;
                const owner = tickerOwned
                    ? new internal_1.Identity({ did: conversion_1.identityIdToString(tickerOwner) }, context)
                    : null;
                if (assetOwned) {
                    status = types_1.TickerReservationStatus.AssetCreated;
                }
                else if (tickerOwned) {
                    status = types_1.TickerReservationStatus.Reserved;
                    if (expiry.isSome) {
                        expiryDate = conversion_1.momentToDate(expiry.unwrap());
                        if (expiryDate < new Date()) {
                            status = types_1.TickerReservationStatus.Free;
                        }
                    }
                }
                else {
                    status = types_1.TickerReservationStatus.Free;
                }
                return {
                    owner,
                    expiryDate,
                    status,
                };
            };
            if (callback) {
                // NOTE @monitz87: the type assertions are necessary because queryMulti doesn't play nice with strict types
                return queryMulti([
                    [asset.tickers, rawTicker],
                    [asset.tokens, rawTicker],
                ], ([registration, token]) => {
                    callback(assembleResult(registration, token));
                });
            }
            // NOTE @monitz87: the type assertions are necessary because queryMulti doesn't play nice with strict types
            const [tickerRegistration, meshAsset] = yield queryMulti([
                [asset.tickers, rawTicker],
                [asset.tokens, rawTicker],
            ]);
            return assembleResult(tickerRegistration, meshAsset);
        });
    }
    /**
     * Determine whether this Ticker Reservation exists on chain
     */
    exists() {
        return __awaiter(this, void 0, void 0, function* () {
            const { ticker, context } = this;
            const tickerSize = yield context.polymeshApi.query.asset.tickers.size(conversion_1.stringToTicker(ticker, context));
            return !tickerSize.isZero();
        });
    }
    /**
     * Return the Reservation's ticker
     */
    toJson() {
        return this.ticker;
    }
}
exports.TickerReservation = TickerReservation;
//# sourceMappingURL=index.js.map