"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 __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getOrdersPaginated = exports.getOpenOrders = exports.getOpenOrdersPaginated = void 0;
const encoding_1 = require("./encoding");
/**
 * Returns an iterator yielding an item for each page of order in the orderbook that is currently being collected.
 * @param contract - to query from
 * @param pageSize - the number of items to fetch per page
 * @param blockNumber - the block number to execute the query at, defaults to "latest" if omitted
 */
function getOpenOrdersPaginated(contract, pageSize, blockNumber) {
    return __asyncGenerator(this, arguments, function* getOpenOrdersPaginated_1() {
        let nextPageUser = "0x0000000000000000000000000000000000000000";
        let nextPageUserOffset = "0";
        let hasNextPage = true;
        if (blockNumber) {
            contract = contract.clone();
            contract.defaultBlock = blockNumber;
        }
        while (hasNextPage) {
            const page = yield __await(contract.methods
                .getOpenOrderBookPaginated([], nextPageUser, nextPageUserOffset, pageSize)
                .call());
            const elements = encoding_1.decodeIndexedOrders(page.elements);
            yield yield __await(elements);
            //Update page info
            hasNextPage = page.hasNextPage;
            nextPageUser = page.nextPageUser;
            nextPageUserOffset = page.nextPageUserOffset;
        }
    });
}
exports.getOpenOrdersPaginated = getOpenOrdersPaginated;
/**
 * Returns open orders in the orderbook.
 * @param contract - to query from
 * @param pageSize - the number of items to fetch per page
 * @param blockNumber - the block number to execute the query at, defaults to "latest" if omitted
 */
function getOpenOrders(contract, pageSize, blockNumber) {
    var e_1, _a;
    return __awaiter(this, void 0, void 0, function* () {
        let allOrders = [];
        try {
            for (var _b = __asyncValues(getOpenOrdersPaginated(contract, pageSize, blockNumber)), _c; _c = yield _b.next(), !_c.done;) {
                const page = _c.value;
                allOrders = allOrders.concat(page);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
        return allOrders;
    });
}
exports.getOpenOrders = getOpenOrders;
/**
 * Returns all orders in the orderbook.
 * @param contract - to query from
 * @param pageSize - the number of items to fetch per page
 * @param blockNumber - the block number to execute the query at, defaults to "latest" if omitted
 */
function getOrdersPaginated(contract, pageSize, blockNumber) {
    return __awaiter(this, void 0, void 0, function* () {
        let orders = [];
        let currentUser = "0x0000000000000000000000000000000000000000";
        let currentOffSet = 0;
        let lastPageSize = pageSize;
        if (blockNumber) {
            contract = contract.clone();
            contract.defaultBlock = blockNumber;
        }
        while (lastPageSize == pageSize) {
            const page = encoding_1.decodeOrders(yield contract.methods
                .getEncodedUsersPaginated(currentUser, currentOffSet, pageSize)
                .call());
            orders = orders.concat(page);
            for (const index in page) {
                if (page[index].user != currentUser) {
                    currentUser = page[index].user;
                    currentOffSet = 0;
                }
                currentOffSet += 1;
            }
            lastPageSize = page.length;
        }
        return orders;
    });
}
exports.getOrdersPaginated = getOrdersPaginated;
