import Transaction from "../../apiwrapper/transaction/Transaction.js";
import AbstractStrategy from "./AbstractStrategy.js";

export default class PossiblePeakStrategy extends AbstractStrategy {
    #lastBuySuggestionTime = 0;

    constructor() {
        super();
        this.#lastBuySuggestionTime = Date.now();
    }

    /**
     * @param {Transaction} transaction 
     * @returns {boolean}
     */
    shouldSell(transaction) {
        const winPercent = (this.getAssetData().getOrderBook().getBestBid().price / transaction.buySettings.price) * 100 - 100;
        
        if(!this.isAllowedToSell(transaction, winPercent)){
            return false;
        }

        return this.getAssetData().getOrderBook().getBestBid().price / transaction.buySettings.price >= 1.015;
    }

    /**
     * @returns {boolean}
     */
    shouldBuy() {
        if (Date.now() < this.#lastBuySuggestionTime + 120000) {
            return false;
        }

        const peakCount = this.getAssetData().getPeakCountInTimeslot('1h');
        const price = this.getAssetData().getOrderBook().getBestBid().price;

        if (peakCount < 2) {
            return false;
        }

        const dataPoints15m = this.getAssetData().getAggregatedData('15m');

        if(dataPoints15m.length == 0){
            return false;
        }

        const avg5Min = dataPoints15m.slice(-5).map(v => v.avgPrice).reduce((a, b) => a+b, 0) / dataPoints15m.length;;
        const avg15Min = dataPoints15m.map(v => v.avgPrice).reduce((a, b) => a+b, 0) / dataPoints15m.length;
        const m5min = dataPoints15m[0].startPrice / dataPoints15m[dataPoints15m.length - 1].endPrice;

        if ((price < avg5Min && avg5Min > avg15Min)
            || (price < avg15Min && m5min > 0.9995)
            || (price < dataPoints15m[dataPoints15m.length - 6].startPrice && price > avg5Min)
        ) {
            this.#lastBuySuggestionTime = Date.now();
            return true;
        }
    }


    /**
     * @param {Transaction} transaction 
     * @returns {boolean}
     */
    shouldCancle(transaction) {
        return false;
    }

    /**
    * @returns {string} string representation of this object
    */
    toJson() {
        const obj = JSON.parse(super.toJson());

        return JSON.stringify(obj);
    }

    /**
     * @param {string} objString 
     * @returns {TestStrategy}
     */
    static fromJson(objString) {
        return new PossiblePeakStrategy();
    }
}