import { Game } from "./game";
import { TimerDisplay } from "../ui";

export class TimedGame extends Game {
    constructor(time, ticker) {
        super();
        this._timeoutId = undefined;
        this.baseTimeout = time;
        this.currentTimeout = time;

        this._timeoutStartTime = undefined;

        this.timerDisplay = new TimerDisplay(() => {
            return this.getRemainingTime();
        }, ticker);
        this._addUiChild(this.timerDisplay.node);
    }

    start() {
        super.start();
        this.timerDisplay.start();
        this._timeoutStartTime = Date.now();
        this._timeoutId = setTimeout(() => {
            this._onTimeout();
        }, this.baseTimeout);
    }

    /* remove t milliseconds to the current timeout (if any) */
    removeTime(t) {
        if (this._timeoutId != undefined) {
            this.currentTimeout = this.getRemainingTime() - t;
            clearTimeout(this._timeoutId);
            if (t <= 0) {
                this._onTimeout();
            } else {
                this._timeoutStartTime = Date.now();
                this._timeoutId = setTimeout(() => {
                    this._onTimeout();
                }, this.currentTimeout);
            }
        }
    }

    reset() {
        super.reset();
        clearTimeout(this._timeoutId);
        this._timeoutId = undefined;
        this._timeoutStartTime = undefined;
        this.currentTimeout = this.baseTimeout;
    }

    end(status) {
        clearTimeout(this._timeoutId);
        super.end(this.getRemainingTime() > 0 ? status : false); // even if for some reason sub class tries to end after timeout, the game is still lost
        this.timerDisplay.stop();
        this._timeoutId = undefined;
    }

    getRemainingTime() {
        if (this._timeoutStartTime && this.currentTimeout) {
            return this.currentTimeout - (Date.now() - this._timeoutStartTime);
        } else {
            return -1;
        }
    }

    _onTimeout() {
        console.log("time end");
        this.end(this.won);
    }
}
