import { useState, useEffect, useRef } from "react";
import { TheAbstractionEngine, Game } from "../engine";

export interface GameCanvasProps {
  width: number;
  height: number;
}

export const GameCanvas = ({ width, height }: GameCanvasProps) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [_game, setGame] = useState<TheAbstractionEngine>();

  useEffect(() => {
    if (canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        const game = new Game();
        const theAbstractionEngine = new TheAbstractionEngine(game, ctx);

        theAbstractionEngine.init().then(() => {
          theAbstractionEngine.play();
          setGame(theAbstractionEngine);
        });

        return () => theAbstractionEngine.stop();
      }
    }
  }, [canvasRef]);

  return (
    <div className="centered-game">
      <canvas ref={canvasRef} width={width} height={height}></canvas>
    </div>
  );
};
