import styles from "./chapter-1.module.css";
import { animationPhases, getAnimationStates } from "./data/index";
import { drawSelect } from "./select";
import { AnimationName } from "./type";

export function chapter1() {
  const canvas = document.getElementById("canvas") as HTMLCanvasElement;
  const ctx = canvas.getContext("2d");

  canvas.classList.add(styles.container);

  const select$ = drawSelect();

  const CANVAS_W = (canvas.width = 600);
  const CANVAS_H = (canvas.height = 600);

  const playerImage = new Image();
  playerImage.src = "/shadow_dog.png";

  const SPRITE_W = 6876 / 12;
  const SPRITE_H = 5230 / 10;
  let stateName: AnimationName = "run";
  let gameFrame = 0;
  const staggerFrame = 5;

  const animationState = getAnimationStates(
    SPRITE_W,
    SPRITE_H,
    animationPhases
  );

  select$.subscribe((event) => {
    stateName = (event.target as HTMLSelectElement).value as AnimationName;
  });

  function animate() {
    if (ctx) {
      ctx.clearRect(0, 0, CANVAS_W, CANVAS_H);
      let position =
        Math.floor(gameFrame / staggerFrame) %
        animationState[stateName].loc.length;
      let frameX = SPRITE_W * position;
      let frameY = animationState[stateName].loc[position].y;

      ctx.drawImage(
        playerImage,
        frameX,
        frameY,
        SPRITE_W,
        SPRITE_H,
        0,
        0,
        SPRITE_W,
        SPRITE_H
      );
      gameFrame++;
      requestAnimationFrame(animate);
    }
  }

  animate();
}
