import Clock from './Clock';

/** Dev clock that exposes keyboard shortcuts for time scaling and pausing. */
export default class DevClock extends Clock
{
    public override name = 'DevClock';

    private readonly keydownHandler = (event: KeyboardEvent) =>
    {
        if (this.timeScale > 0)
        {
            this.previousNonZeroTimeScale = this.timeScale;
        }

        switch (event.code)
        {
            case 'KeyD':
                this.setTimeScale(0.00001);
                break;
        }
    };

    private readonly keyupHandler = (event: KeyboardEvent) =>
    {
        if (this.timeScale > 0)
        {
            this.previousNonZeroTimeScale = this.timeScale;
        }

        switch (event.code)
        {
            case 'KeyD':
            case 'Digit0':
            case 'Digit1':
                this.setTimeScale(1);
                break;
            case 'Digit2':
                this.setTimeScale(2);
                break;
            case 'Digit3':
                this.setTimeScale(3);
                break;
            case 'Digit8':
                this.setTimeScale(0.25);
                break;
            case 'Digit9':
                this.setTimeScale(0.5);
                break;
            case 'ArrowLeft':
                this.setTimeScale(this.previousNonZeroTimeScale * 0.5);
                break;
            case 'ArrowRight':
                this.setTimeScale(this.previousNonZeroTimeScale * 2);
                break;
            case 'ArrowUp':
                this.setTimeScale(1);
                break;
            case 'ArrowDown':
                this.setTimeScale(this.timeScale ? 0 : this.previousNonZeroTimeScale);
                break;
            case 'KeyP':
                this.togglePause();
                break;
        }
    };

    constructor()
    {
        super();
        window.addEventListener('keydown', this.keydownHandler);
        window.addEventListener('keyup', this.keyupHandler);
    }

    public override pause(): void
    {
        super.pause();
        // eslint-disable-next-line no-console
        console.log('Paused');
    }

    public override resume(): void
    {
        super.resume();
        // eslint-disable-next-line no-console
        console.log('Resumed');
    }

    /** Toggles paused state. */
    public togglePause(): void
    {
        if (this.paused)
        {
            this.resume();
        }
        else
        {
            this.pause();
        }
    }

    public override dispose(): void
    {
        window.removeEventListener('keydown', this.keydownHandler);
        window.removeEventListener('keyup', this.keyupHandler);
        super.dispose();
    }
}
