"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 __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); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bn_js_1 = __importDefault(require("bn.js"));
const onchain_reading_1 = require("../src/onchain_reading");
const orderbook_1 = require("../src/orderbook");
const fraction_1 = require("../src/fraction");
const logging_1 = require("../src/logging");
const log = logging_1.factory.getLogger("scripts.setup_environment");
const BatchExchangeViewer = artifacts.require("BatchExchangeViewer");
const argv = require("yargs")
    .option("sellToken", {
    describe: "the token you are looking to sell",
})
    .option("buyToken", {
    describe: "the token you are looking to sell",
})
    .option("sellAmount", {
    describe: "the amount you are looking to sell",
})
    .option("hops", {
    default: 1,
    describe: "Number of hops in potential ring trades",
})
    .option("pageSize", {
    default: 100,
    describe: "The page  size for the function getOrdersPaginated",
})
    .demand(["sellToken", "buyToken", "sellAmount"])
    .version(false).argv;
const addItemToOrderbooks = function (orderbooks, item) {
    let orderbook = new orderbook_1.Orderbook(item.sellToken, item.buyToken);
    if (!orderbooks.has(orderbook.pair())) {
        orderbooks.set(orderbook.pair(), orderbook);
    }
    // We have explicitly ensured above that this will not be null.
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    orderbook = orderbooks.get(orderbook.pair());
    const price = new fraction_1.Fraction(item.priceNumerator, item.priceDenominator);
    const volume = new fraction_1.Fraction(item.remainingAmount.gt(item.sellTokenBalance)
        ? item.sellTokenBalance
        : item.remainingAmount, 1);
    // Smaller orders cannot be matched anyways
    if (volume.gt(new fraction_1.Fraction(10000, 1))) {
        orderbook.addAsk(new orderbook_1.Offer(price, volume));
    }
};
const getAllOrderbooks = function (instance, pageSize) {
    var e_1, _a;
    return __awaiter(this, void 0, void 0, function* () {
        const orderbooks = new Map();
        try {
            for (var _b = __asyncValues(onchain_reading_1.getOpenOrdersPaginated(instance.contract, pageSize)), _c; _c = yield _b.next(), !_c.done;) {
                const page = _c.value;
                log.info("Fetched Page");
                page.forEach((item) => {
                    addItemToOrderbooks(orderbooks, item);
                });
            }
        }
        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 orderbooks;
    });
};
module.exports = (callback) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const sellAmount = new bn_js_1.default(argv.sellAmount);
        const instance = yield BatchExchangeViewer.deployed();
        const orderbooks = yield getAllOrderbooks(instance, argv.pageSize);
        const transitive_book = orderbook_1.transitiveOrderbook(orderbooks, argv.sellToken, argv.buyToken, parseInt(argv.hops));
        const price = transitive_book.priceToSellBaseToken(sellAmount);
        log.info(`Suggested price to sell ${argv.sellAmount} of token ${argv.sellToken} for token ${argv.buyToken} is: ${price === null || price === void 0 ? void 0 : price.toNumber()}`);
        callback();
    }
    catch (error) {
        callback(error);
    }
});
