import { Pane } from 'tweakpane';
import Scenes, { type SceneLike, type SceneRoot } from './Scenes';

/** Adds tweakpane controls for managing registered scenes during development. */
export default class DevScenes extends Scenes
{
    public readonly pane: Pane;
    public readonly backPanelControlsName = 'Scenes';

    private readonly keyHandler: (event: KeyboardEvent) => void;

    constructor(root: SceneRoot)
    {
        super(root);
        this.pane = new Pane({ title: 'Scenes' });
        (this.pane as unknown as { containerElem_: HTMLElement }).containerElem_.style.zIndex = '100';
        this.keyHandler = (event: KeyboardEvent) =>
        {
            if (event.key.toLowerCase() === 'h')
            {
                //@ts-expect-error types
                this.pane.hidden = !this.pane.hidden;
            }
        };
        document.addEventListener('keydown', this.keyHandler);
    }

    public override add(key: string, scene: SceneLike): void
    {
        super.add(key, scene);
        //@ts-expect-error types
        const folder = this.pane.addFolder({ title: key, expanded: false });

        const runBtn = folder.addButton({ title: 'run' });

        runBtn.on('click', () => this.run(key, {}));

        const stopBtn = folder.addButton({ title: 'stop' });

        stopBtn.on('click', () => this.stop(key));

        const pauseBtn = folder.addButton({ title: 'pause' });

        pauseBtn.on('click', () => this.pause(key));

        const resumeBtn = folder.addButton({ title: 'resume' });

        resumeBtn.on('click', () => this.resume(key));

        if (scene.inputs)
        {
            Object.keys(scene.inputs).forEach((inputKey) =>
            {
                const value = (scene.inputs as Record<string, unknown>)[inputKey];

                if (Array.isArray(value) || value === undefined)
                {
                    return;
                }

                folder.addBinding(scene.inputs as Record<string, unknown>, inputKey as string);
            });
        }
    }

    public override update(dt: number): void
    {
        super.update(dt);
        //@ts-expect-error types
        this.pane.refresh();
    }

    public override dispose(): void
    {
        super.dispose();
        document.removeEventListener('keydown', this.keyHandler);
        this.pane.dispose();
    }
}
