import TradingPair from "../../apiwrapper/assets/TradingPair.js";
import Transaction from "../../apiwrapper/transaction/Transaction.js";
import TransactionPhase from "../../apiwrapper/transaction/TransactionPhase.js";
import AssetData from "../data/asset/AssetData.js";
import AbstractStrategy from "../strategy/AbstractStrategy.js";
import AbstractWorker from "./AbstractWorker.js";

export default class SingleTransactionTestWorker extends AbstractWorker{
    buyDone = false;
    sellDone = false;
    starttime = -1;

    /**
     * @param {string} name 
     * @param {TradingPair} tradingPair 
     * @param {AbstractStrategy} strategy 
     */
    constructor(name, tradingPair, strategy){
        super(name, tradingPair, strategy);
        this.starttime = Date.now();
    }

    /**
     * @param {string} dataPath path to data directory
     */
    onInit(dataPath){
        this.getLogger().debug("Worker " + this.getName() + " initialized!");
    }

    /**
     * @param {AssetData} assetData 
     * @param {Transaction[]} transactions 
     * @param {number} transactionlimit
     */
    onUpdate(assetData, transactions, transactionlimit){
        if(Date.now() - this.starttime < 30000){
            return;
        }

        this.getStrategy().setAssetData(assetData);
        const bestBid = this.getStrategy().getAssetData().getOrderBook().getBestBid();

        if(bestBid == null) {
            return;
        }

        const price = parseFloat(bestBid.price);

        if(!this.buyDone){
            this.getApiProvider().requestBuy(this, Math.round(10 / price), price);
            this.starttime = Date.now();
            this.buyDone = true;
        }

        if(!this.sellDone && transactions.length > 0 && transactions[0].phase == TransactionPhase.BUY_DONE){
            this.getApiProvider().requestSell(this, transactions[0], assetData.getOrderBook().getBestAsk().price);
            this.sellDone = true;
        }
    }

    /**
    * @returns {string} string representation of this object
    */
    toJson() {
        return super.toJson();
    }

    /**
     * @param {string} objString 
     * @returns {AbstractWorker}
     */
    static fromJson(objString) {
        return super.fromJson(objString, new SingleTransactionTestWorker());
    }
}