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

export default class Simple24hStrategy 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(winPercent >= 3){
            return true;
        }

        if(winPercent < 0.6){
            return false;
        }
        
        const grades = this.#getGrades();

        if(grades == null){
            return false;
        }

        const grad15min = grades[0];
        const grad60min = grades[1];
        const priceChangePercent24h = this.getAssetData().get24hPriceChangePercent();

        return priceChangePercent24h < 0.05 || grad15min <  grad60min * 0.97;
    }

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

        const grades = this.#getGrades();

        if(grades == null){
            return false;
        }

        const grad15min = grades[0];
        const grad60min = grades[1];
        const priceChangePercent24h = this.getAssetData().get24hPriceChangePercent();
        
        // up trend
        if(priceChangePercent24h > 2 && grad15min < 0 && grad60min > 0){
            this.#lastBuySuggestionTime = Date.now();
            return true;
        }

        // down trend
        if(priceChangePercent24h < -2 && (grad60min < grad15min || grad15min > 0.15 && grad60min > -0.02)){
            this.#lastBuySuggestionTime = Date.now();
            return true;
        }

        return false;
    }

    /**
     * @returns {[number, number] | null}
     */
    #getGrades(){
        const dataPoints1h = this.getAssetData().getAggregatedData('1h');

        if(dataPoints1h.length < 60){
            return null;
        }

        const endPrice = dataPoints1h[dataPoints1h.length - 1].endPrice;
        const grad15min = (endPrice - dataPoints1h[dataPoints1h - 15].startPrice) / 15;
        const grad60min = (endPrice - dataPoints1h[dataPoints1h - 60].startPrice) / 60;

        return [grad15min, grad60min];
    }

    /**
     * @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 Simple24hStrategy();
    }
}