"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.Offering = void 0;
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const internal_1 = require("../../../internal");
const queries_1 = require("../../../middleware/queries");
const conversion_1 = require("../../../utils/conversion");
const internal_2 = require("../../../utils/internal");
/**
 * Represents an Asset Offering in the Polymesh blockchain
 */
class Offering extends internal_1.Entity {
    /**
     * @hidden
     */
    constructor(identifiers, context) {
        super(identifiers, context);
        const { id, ticker } = identifiers;
        this.id = id;
        this.asset = new internal_1.Asset({ ticker }, context);
        this.freeze = internal_2.createProcedureMethod({
            getProcedureAndArgs: () => [internal_1.toggleFreezeOffering, { ticker, id, freeze: true }],
            voidArgs: true,
        }, context);
        this.unfreeze = internal_2.createProcedureMethod({
            getProcedureAndArgs: () => [internal_1.toggleFreezeOffering, { ticker, id, freeze: false }],
            voidArgs: true,
        }, context);
        this.close = internal_2.createProcedureMethod({ getProcedureAndArgs: () => [internal_1.closeOffering, { ticker, id }], voidArgs: true }, context);
        this.modifyTimes = internal_2.createProcedureMethod({ getProcedureAndArgs: args => [internal_1.modifyStoTimes, Object.assign({ ticker, id }, args)] }, context);
        this.invest = internal_2.createProcedureMethod({ getProcedureAndArgs: args => [internal_1.investInOffering, Object.assign({ ticker, id }, args)] }, context);
    }
    /**
     * @hidden
     * Check if a value is of type [[UniqueIdentifiers]]
     */
    static isUniqueIdentifiers(identifier) {
        const { id, ticker } = identifier;
        return id instanceof bignumber_js_1.default && typeof ticker === 'string';
    }
    // eslint-disable-next-line require-jsdoc
    details(callback) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context: { polymeshApi: { query: { sto }, }, }, id, asset: { ticker }, context, } = this;
            const assembleResult = (rawFundraiser, rawName) => conversion_1.fundraiserToOfferingDetails(rawFundraiser.unwrap(), rawName, context);
            const rawTicker = conversion_1.stringToTicker(ticker, context);
            const rawU64 = conversion_1.numberToU64(id, context);
            const fetchName = () => sto.fundraiserNames(rawTicker, rawU64);
            if (callback) {
                const fundraiserName = yield fetchName();
                return sto.fundraisers(rawTicker, rawU64, fundraiserData => {
                    callback(assembleResult(fundraiserData, fundraiserName));
                });
            }
            const [fundraiser, name] = yield Promise.all([sto.fundraisers(rawTicker, rawU64), fetchName()]);
            return assembleResult(fundraiser, name);
        });
    }
    /**
     * Retrieve all investments made on this Offering
     *
     * @param opts.size - page size
     * @param opts.start - page offset
     *
     * @note supports pagination
     * @note uses the middleware
     */
    getInvestments(opts = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            const { context, id, asset: { ticker }, } = this;
            const { size, start } = opts;
            const result = yield context.queryMiddleware(queries_1.investments({
                stoId: id.toNumber(),
                ticker: ticker,
                count: size,
                skip: start,
            }));
            const { data: { investments: investmentsResult }, } = result;
            /* eslint-disable @typescript-eslint/no-non-null-assertion */
            const { items, totalCount: count } = investmentsResult;
            const data = [];
            items.forEach(item => {
                const { investor: did, offeringTokenAmount, raiseTokenAmount } = item;
                data.push({
                    investor: new internal_1.Identity({ did }, context),
                    soldAmount: new bignumber_js_1.default(offeringTokenAmount).shiftedBy(-6),
                    investedAmount: new bignumber_js_1.default(raiseTokenAmount).shiftedBy(-6),
                });
            });
            /* eslint-enable @typescript-eslint/no-non-null-assertion */
            const next = internal_2.calculateNextKey(count, size, start);
            return {
                data,
                next,
                count,
            };
        });
    }
    /**
     * Determine whether this Offering exists on chain
     */
    exists() {
        return __awaiter(this, void 0, void 0, function* () {
            const { asset: { ticker }, id, context, } = this;
            const fundraiser = yield context.polymeshApi.query.sto.fundraisers(conversion_1.stringToTicker(ticker, context), conversion_1.numberToU64(id, context));
            return fundraiser.isSome;
        });
    }
    /**
     * Return the Offering's ID and Asset ticker
     */
    toJson() {
        const { asset, id } = this;
        return internal_2.toHumanReadable({
            ticker: asset,
            id,
        });
    }
}
exports.Offering = Offering;
//# sourceMappingURL=index.js.map