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 = setInterval(() => {
            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 = setInterval(() => {
                    this._onTimeout();
                }, this.currentTimeout);
            }
        }
    }

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

    end(status) {
        super.end(status);
        this.timerDisplay.stop();
        clearTimeout(this._timeoutId);
        this._timeoutId = undefined;
    }

    getRemainingTime() {
        return this.currentTimeout - (Date.now() - this._timeoutStartTime);
    }

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