"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.Assets = void 0;
const internal_1 = require("./internal");
const types_1 = require("./types");
const conversion_1 = require("./utils/conversion");
const internal_2 = require("./utils/internal");
/**
 * Handles all Asset related functionality
 */
class Assets {
    /**
     * @hidden
     */
    constructor(context) {
        this.context = context;
        this.reserveTicker = internal_2.createProcedureMethod({
            getProcedureAndArgs: args => [internal_1.reserveTicker, args],
        }, context);
        this.claimClassicTicker = internal_2.createProcedureMethod({
            getProcedureAndArgs: args => [internal_1.claimClassicTicker, args],
        }, context);
        this.createAsset = internal_2.createProcedureMethod({
            getProcedureAndArgs: args => [internal_1.createAsset, Object.assign({ reservationRequired: false }, args)],
        }, context);
    }
    // eslint-disable-next-line require-jsdoc
    isTickerAvailable(args, callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const reservation = new internal_1.TickerReservation(args, this.context);
            if (callback) {
                return reservation.details(({ status: reservationStatus }) => {
                    // eslint-disable-next-line standard/no-callback-literal
                    callback(reservationStatus === types_1.TickerReservationStatus.Free);
                });
            }
            const { status } = yield reservation.details();
            return status === types_1.TickerReservationStatus.Free;
        });
    }
    /**
     * Retrieve all the ticker reservations currently owned by an Identity. This doesn't include Assets that
     *   have already been launched
     *
     * @param args.owner - defaults to the signing Identity
     *
     * @note reservations with unreadable characters in their tickers will be left out
     */
    getTickerReservations(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query }, }, context, } = this;
            const did = yield internal_2.getDid(args === null || args === void 0 ? void 0 : args.owner, context);
            const entries = yield query.asset.assetOwnershipRelations.entries(conversion_1.stringToIdentityId(did, context));
            return entries.reduce((result, [key, relation]) => {
                if (relation.isTickerOwned) {
                    const ticker = conversion_1.tickerToString(key.args[1]);
                    if (internal_2.isPrintableAscii(ticker)) {
                        return [...result, new internal_1.TickerReservation({ ticker }, context)];
                    }
                }
                return result;
            }, []);
        });
    }
    /**
     * Retrieve a Ticker Reservation
     *
     * @param args.ticker - Asset ticker
     */
    getTickerReservation(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { ticker } = args;
            const { context: { polymeshApi: { query: { asset }, }, }, context, } = this;
            const { owner, expiry } = yield asset.tickers(conversion_1.stringToTicker(ticker, context));
            if (!owner.isEmpty) {
                if (!expiry.isNone) {
                    return new internal_1.TickerReservation({ ticker }, context);
                }
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.UnmetPrerequisite,
                    message: `${ticker} Asset has been created`,
                });
            }
            throw new internal_1.PolymeshError({
                code: types_1.ErrorCode.UnmetPrerequisite,
                message: `There is no reservation for ${ticker} ticker`,
            });
        });
    }
    /**
     * Retrieve all of the Assets owned by an Identity
     *
     * @param args.owner - Identity representation or Identity ID as stored in the blockchain
     *
     * @note Assets with unreadable characters in their tickers will be left out
     */
    getAssets(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query }, }, context, } = this;
            const did = yield internal_2.getDid(args === null || args === void 0 ? void 0 : args.owner, context);
            const entries = yield query.asset.assetOwnershipRelations.entries(conversion_1.stringToIdentityId(did, context));
            return entries.reduce((result, [key, relation]) => {
                if (relation.isAssetOwned) {
                    const ticker = conversion_1.tickerToString(key.args[1]);
                    if (internal_2.isPrintableAscii(ticker)) {
                        return [...result, new internal_1.Asset({ ticker }, context)];
                    }
                }
                return result;
            }, []);
        });
    }
    /**
     * Retrieve an Asset
     *
     * @param args.ticker - Asset ticker
     */
    getAsset(args) {
        return __awaiter(this, void 0, void 0, function* () {
            const { ticker } = args;
            const asset = new internal_1.Asset({ ticker }, this.context);
            const exists = yield asset.exists();
            if (!exists) {
                throw new internal_1.PolymeshError({
                    code: types_1.ErrorCode.DataUnavailable,
                    message: `There is no Asset with ticker "${ticker}"`,
                });
            }
            return asset;
        });
    }
}
exports.Assets = Assets;
//# sourceMappingURL=Assets.js.map