import TradingPairs from "../apiwrapper/assets/TraidingPairs.js";
import Transaction from "../apiwrapper/transaction/Transaction.js";
import WebViewDataProvider from "../webview/WebViewDataProvider.js";
import AssetData from "./data/asset/AssetData.js";
import TradingBot from "./TradingBot.js";

export default class TradingBotRestDataProvider extends WebViewDataProvider {
    /**
     * @type {TradingBot}
     */
    #tradingBot = null;

    /**
     * @param {TradingBot} tradingBot 
     */
    constructor(tradingBot) {
        super();
        this.#tradingBot = tradingBot;
    }

    /**
     * @returns {string[]}
     */
    getAvailableAssets() {
        return this.#tradingBot.getAssetDataCollector().getManagedAssets().map(tp => tp.getKey());
    }

    /**
     * @param {string} symbol 
     * @returns {OrderBook}
     */
    getOrderBook(symbol) {
        return this.getAssetData(symbol).getOrderBook();
    }

    /**
     * @param {*} symbol 
     * @returns {AssetData}
     */
    getAssetData(symbol){
        return this.#tradingBot.getAssetDataCollector().getAssetData(symbol);
    }

    /**
     * @param {string} symbol 
     * @returns {Transaction[]}
     */
    getActiveTransactions(symbol = null) {
        if(symbol == null){
            return this.#tradingBot.getTransactions().sort((t1, t2) => t1.timestamp - t2.timestamp);
        } else {
            return this.#tradingBot.getTransactionsByAsset(TradingPairs.fromString(symbol)).sort((t1, t2) => t1.timestamp - t2.timestamp);
        }
    }

    /**
     * @param {string} symbol 
     * @returns {Transaction[]}
     */
    getAllTransactions(symbol = null) {
        const tp = TradingPairs.fromString(symbol);
        if(symbol == null){
            return this.#tradingBot.getTransactions().concat(this.#tradingBot.getClosedTransactions()).sort((t1, t2) => t1.timestamp - t2.timestamp);
        } else {
            return this.#tradingBot.getTransactionsByAsset(tp).concat(this.#tradingBot.getClosedTransactionsByAsset(tp)).sort((t1, t2) => t1.timestamp - t2.timestamp);
        }
    }

    /**
     * @returns {string[]}
     */
    getExistingTradingPairs() {
        return TradingPairs.TRADING_PAIRS.map(tp => tp.getKey());
    }

    /**
     * @type {Map<string, number>}
     */
    getBalances() {
        return this.#tradingBot.getAccountInfo().getBalances();
    }

    /**
     * @returns {AbstractWorker[]}
     */
    getWorkers() {
        return Array.from(this.#tradingBot.getWorker().values());
    }
}