import { Assets, Container, Sprite, Ticker } from "pixi.js";
import bgImg from "@/assets/GamePage/bg.jpg";
import { Joystick } from "@/pages/GamePage/Components/Joystick.ts";
import 'pixi.js/math-extras';
import { Snake } from "@/pages/GamePage/Components/Snake.ts";
import { ElementMgr } from "@/pages/GamePage/Components/ElementMgr.ts";
import { mapTop } from "@/pages/GamePage/config/Config.ts";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import {Element} from "./Components/Element/Element.ts";

import { Response, Body } from "detect-collisions";

export class Game extends Container {

  joystick: Joystick = null;
  private snake: Snake;
  private mapCtn: Container;

  private elementMgr: ElementMgr;


  constructor() {
    super();
    this.initUI();
  }

  initUI() {

    const bg = this.addChild(new Sprite());
    Assets.load(bgImg).then((texture) => bg.texture = texture);

    this.joystick = this.addChild(new Joystick());
    this.joystick.visible = false;

    this.mapCtn = this.addChild(new Container());
    this.mapCtn.y = mapTop;

    this.elementMgr = new ElementMgr(this.mapCtn);
    this.elementMgr.start();

    this.snake = this.mapCtn.addChild(new Snake());
    this.snake.init();

    this.on("pointerdown", this.onPointerDown, this);
    this.on("pointerup", this.onPointerUp, this);
  }


  onPointerDown(e: any) {
    this.joystick.visible = true;
    this.joystick.x = e.data.global.x;
    this.joystick.y = e.data.global.y;
    this.joystick.handlePointerDown(e);
  }

  onPointerUp(e: any) {
    this.joystick.visible = false;
  }

  colliderCallback = (result: Response) => {
    const {
      a, b,
      aInB, bInA,
      overlap, overlapV, overlapN
    } = result;

    const { userData: { ele } } = b as Body<{ele: Element}>;
    ele.beEaten(this.snake.head);
  }

  onUpdate(time: Ticker) {
    const dt = time.deltaMS / 1000;
    this.snake.dir.copyFrom(this.joystick.dir);
    this.snake.onUpdate(dt);
    collisionSys.checkOne(this.snake.collider, this.colliderCallback);
  }

  destroy() {


    super.destroy();
  }
}
