import { Assets, Container, Sprite, Point } from "pixi.js";
import { getApp } from "@/pages/GamePage/GamePage.tsx";
import { GameEvent } from "@/pages/GamePage/GameEvent.ts";

const radius = 210 / 2;

export class Joystick extends Container {

  handle: Sprite = null;

  dir: Point = new Point(1, 0);

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

  initUI() {
    const bg = new Sprite(Assets.get("摇杆背景.png"));
    bg.anchor.set(0.5, 0.5);
    this.addChild(bg);

    this.handle = new Sprite(Assets.get("摇杆手柄.png"));
    this.handle.anchor.set(0.5, 0.5);
    this.addChild(this.handle);
    this.handle.on("pointerdown", this.handlePointerDown, this);
  }

  calcDir(x: number, y: number) {
    const dx = x - this.x;
    const dy = y - this.y;

    if(dx == 0 && dy == 0) return;

    this.dir.set(dx, dy);

    const len = this.dir.magnitude();
    if (len > radius) {
      this.dir.multiplyScalar(radius / len, this.dir);
    }

    this.handle.position.set(this.dir.x, this.dir.y);

    this.dir.normalize(this.dir);

    this.emit(GameEvent.DIR_CHANGE, this.dir);
  }

  handlePointerDown = (e: any) => {
    this.calcDir(e.data.global.x, e.data.global.y);

    const handlePointerMove = (e: any) => {
      this.calcDir(e.data.global.x, e.data.global.y);
    }

    const handlePointerUp = (e) => {
      this.calcDir(e.data.global.x, e.data.global.y);
      this.handle.position.set(0, 0);
      getApp().stage.off("pointermove", handlePointerMove);
      getApp().stage.off("pointerup", handlePointerUp);
    }
    getApp().stage.on("pointermove", handlePointerMove);
    getApp().stage.on("pointerup", handlePointerUp);
  }

}
