"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.orders = exports.Sides = void 0;
require("@equilab/api/equilibrium/interfaces/types-lookup");
const util_1 = require("@polkadot/api-derive/util");
const bn_js_1 = __importDefault(require("bn.js"));
const operators_1 = require("rxjs/operators");
const util_2 = require("../../util");
const bnToStringWithBase = (num, dec = 9) => {
    const TEN = new bn_js_1.default(10);
    const pow = new bn_js_1.default(dec);
    const div = TEN.pow(pow);
    const int = num.div(div);
    const fra = num.mod(div);
    const res = `${int.toString(10)}.${fra.toString(10).padStart(dec, "0")}`;
    return res;
};
var Sides;
(function (Sides) {
    Sides["Buy"] = "buy";
    Sides["Sell"] = "sell";
})(Sides = exports.Sides || (exports.Sides = {}));
const orders = (instanceId, api) => (0, util_1.memo)(instanceId, (token) => {
    const asset = (0, util_2.u64FromCurrency)(token);
    return api.query.eqDex.actualChunksByAsset(asset).pipe((0, operators_1.mergeMap)((chunks) => api.query.eqDex.ordersByAssetAndChunkKey.multi(chunks.map((chunk) => [asset, chunk]))), (0, operators_1.map)((bundles) => bundles.reduce((prev, bundle) => {
        return [
            ...prev,
            ...bundle.map((order) => ({
                id: order.orderId.toNumber(),
                account: order.accountId.toString(),
                side: order.side.isBuy ? Sides.Buy : Sides.Sell,
                price: bnToStringWithBase(order.price),
                amount: bnToStringWithBase(order.amount),
                createdAt: order.createdAt.toString(10),
                expirationTime: order.expirationTime.toString(10),
            })),
        ];
    }, [])));
});
exports.orders = orders;
