import { Game } from ".";
import { Miscellaneous, loadAssets } from "./config";
import {
  Player,
  Wall,
  LambdaFactory,
  Key,
  LockedDoor,
  Curry,
  FunctionApplication,
} from "./entities";
import {
  Grid,
  FacingDirection,
  Input,
  Render,
  Collision,
  GridSpawner,
  Life,
  Music,
} from "./systems";

export class TheAbstractionEngine {
  private game: Game;
  private ctx: CanvasRenderingContext2D;
  private animationFrameId: number | null;

  constructor(game: Game, ctx: CanvasRenderingContext2D) {
    this.game = game;
    this.ctx = ctx;
    this.animationFrameId = null;
  }

  public async init() {
    await loadAssets();

    const inputSystem = new Input();
    this.addWindowEventListenersToInputSystem(inputSystem);

    const facingDirectionSystem = new FacingDirection(inputSystem);

    [
      inputSystem,
      facingDirectionSystem,
      new Grid(
        { width: Miscellaneous.GRID_COLUMNS, height: Miscellaneous.GRID_ROWS },
        {
          width: Miscellaneous.GRID_CELL_WIDTH,
          height: Miscellaneous.GRID_CELL_HEIGHT,
        },
      ),
      new GridSpawner(),
      new Collision(),
      new Life(),
      new Music(),
      new Render(this.ctx),
    ].forEach((system) => this.game.addSystem(system));

    const player = new Player();
    this.game.addEntity(player);

    const wall = new Wall({ x: 5, y: 3 });
    this.game.addEntity(wall);

    const factory = new LambdaFactory({ x: 3, y: 3 }, "(λ (x) . x)", 10);
    this.game.addEntity(factory);

    const lockedDoor = new LockedDoor({ x: 8, y: 8 });
    this.game.addEntity(lockedDoor);

    const key = new Key({ x: 7, y: 7 });
    this.game.addEntity(key);

    const curry = new Curry({ x: 9, y: 8 });
    this.game.addEntity(curry);

    const application = new FunctionApplication({ x: 5, y: 5 }, "(_INPUT key)");
    this.game.addEntity(application);
  }

  public play() {
    this.game.start();

    const loop = (timestamp: number) => {
      this.game.doGameLoop(timestamp);
      this.animationFrameId = requestAnimationFrame(loop); // tail call recursion! /s
    };
    this.animationFrameId = requestAnimationFrame(loop);
  }

  public stop() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }

  private addWindowEventListenersToInputSystem(input: Input) {
    this.ctx.canvas.addEventListener("keydown", (e) => {
      if (!e.repeat) {
        input.keyPressed(e.key.toLowerCase());
      }
    });

    this.ctx.canvas.addEventListener("keyup", (e) =>
      input.keyReleased(e.key.toLowerCase()),
    );

    this.ctx.canvas.addEventListener("blur", () => input.clearKeys());

    this.ctx.canvas.addEventListener("mousemove", (e) => {
      const canvas = this.ctx.canvas;
      const rect = canvas.getBoundingClientRect();

      const scaleX = canvas.width / rect.width;
      const scaleY = canvas.height / rect.height;

      const x = (e.clientX - rect.left) * scaleX;
      const y = (e.clientY - rect.top) * scaleY;

      input.setMousePosition({ x, y });
    });
  }
}
