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

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

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

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

    useLayoutEffect(() => {
        if (game.current === null) {

            game.current = StartGame("cog-shooter-game-container");

            if (typeof ref === 'function') {
                ref({ game: game.current, scene: null });
            } else if (ref) {
                ref.current = { game: game.current, scene: null };
            }

        }

        return () => {
            if (game.current) {
                game.current.destroy(true);
                if (game.current !== null) {
                    game.current = null;
                }
            }
        }
    }, [ref]);

    useEffect(() => {
        EventBus.on('scene-ready', (scene_instance: GameScene) => {
            if (currentActiveScene && typeof currentActiveScene === 'function') {
                currentActiveScene(scene_instance);
            }

            if (typeof ref === 'function') {
                ref({ game: game.current, scene: scene_instance });
            } else if (ref) {
                ref.current = { game: game.current, scene: scene_instance };
            }

        });
        return () => {
            EventBus.removeListener('scene-ready');
        }
    }, [currentActiveScene, ref]);

    return (
        <div id="cog-shooter-game-container"></div>
    );

});
