"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;
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)}`;
    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: (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.order_id.toNumber(),
                account: order.account_id.toString(),
                side: order.side.isBuy ? Sides.Buy : Sides.Sell,
                price: bnToStringWithBase(order.price),
                amount: bnToStringWithBase(order.amount, 18),
                createdAt: order.created_at.toString(10),
                expirationTime: order.expiration_time.toString(10),
            })),
        ];
    }, [])));
});
exports.orders = orders;
