import { forwardRef, useLayoutEffect, useRef } from 'react';
import StartGame from './main';
import { EventBus } from './EventBus';
import PlayScene from './scenes/PlayScene';

export interface IRefPhaserGame {
    game: Phaser.Game | null;
    scene: PlayScene | null;
}

interface IProps {
    currentActiveScene?: (scene_instance: PlayScene) => void;
}

export const PhaserGame = forwardRef<IRefPhaserGame, IProps>(function PhaserGame({ currentActiveScene }, ref) {
    const game = useRef<Phaser.Game | null>(null);

    useLayoutEffect(() => {
        let readyScene: PlayScene | null = null;

        const assignRef = (scene: PlayScene | null) => {
            if (typeof ref === 'function') {
                ref({ game: game.current, scene });
            } else if (ref) {
                ref.current = { game: game.current, scene };
            }
        };

        const setCurrentScene = (scene_instance: PlayScene) => {
            readyScene = scene_instance;

            if (currentActiveScene && typeof currentActiveScene === 'function') {
                currentActiveScene(scene_instance);
            }

            assignRef(scene_instance);
        };

        EventBus.on('current-scene-ready', setCurrentScene);

        if (game.current === null) {
            game.current = StartGame(`skiing-game-tutorial-container`);
            assignRef(readyScene);
        }

        return () => {
            EventBus.removeListener('current-scene-ready', setCurrentScene);
            if (game.current) {
                game.current.destroy(true);
                if (game.current !== null) {
                    game.current = null;
                }
            }
        }
    }, [currentActiveScene, ref]);

    return (
        <div id={`skiing-game-tutorial-container`}></div>
    );

});
