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

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

export const GameCanvas = ({ width, height }: GameCanvasProps) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [game, setGame] = useState<TheAbstractionEngine>();
  const [ready, setReady] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (canvasRef.current && !game) {
      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();
          canvas.focus();

          setGame(theAbstractionEngine);
          setLoading(false);
        });

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

  if (ready) {
    return (
      <div className="centered-game">
        <canvas
          id={Miscellaneous.CANVAS_ID}
          tabIndex={1}
          ref={canvasRef}
          width={loading ? 50 : width}
          height={loading ? 50 : height}
        ></canvas>
        {loading && <span className="loading">Loading...</span>}
      </div>
    );
  }

  return (
    <div className="centered-game">
      <Title setReady={setReady} />
    </div>
  );
};
