import { LevelBase } from "@/pages/GamePage/Components/LevelBase.ts";
import { Assets, Circle, Sprite } from "pixi.js";
import { Ease, Tween } from "@/core/tween";
import { GameEvent, globalEvent } from "@/pages/GamePage/GameEvent.ts";

export class Level13 extends LevelBase {

  level: number = 13;

  A: Sprite;
  B: Sprite;
  C: Sprite;

  right: Sprite;
  error: Sprite;

  onLoad() {
    super.onLoad();

    this.addChild(new Sprite(Assets.get(`level${this.level}/D.png`)))
      .position.set(198, 687);

    this.C = this.addChild(new Sprite(Assets.get(`level${this.level}/C.png`)));
    this.C.position.set(198, 687);

    this.B = this.addChild(new Sprite(Assets.get(`level${this.level}/B.png`)));
    this.B.position.set(463, 1086);

    this.A = this.addChild(new Sprite(Assets.get(`level${this.level}/A.png`)));
    this.A.position.set(161, 1086);

    this.right = this.addChild(new Sprite(Assets.get(`level${this.level}/right.png`)));
    this.right.position.set(255, 916);
    this.right.alpha = 0;
    this.right.interactive = false;
    this.right.eventMode = "none";

    [this.A, this.B, this.C].forEach((item) => {
      item.on("pointerdown", this.onAPointerDown, this);
      item.on("pointerup", this.onAPointerUp, this);
      item.on("globalpointermove", this.onAPointerMove, this);
    });

  }

  target: Sprite = null;
  pos: { x: number, y: number } = null;

  onAPointerUp(e) {
    this.pos = null;
    this.target = null;
  }

  onAPointerDown(e) {
    this.target = e.target;
    const { x, y } = e.data.global;
    this.pos = {
      x: x - e.target.x,
      y: y - e.target.y
    }
  }

  onAPointerMove(e) {
    if (!this.pos) return;
    const { x, y } = e.data.global;
    const nx = x - this.pos.x;
    const ny = y - this.pos.y;
    this.target.position.set(nx, ny);

    const { x: cx, y: cy } = this.C;

    if (
      cx < 10 || cx > 410
      || cy < 480 || cy > 900
    ) {
      this.setTouchEnable(false);
      Tween.get(this.right)
        .to({ alpha: 1 }, 444, Ease.quadInOut)
        .wait(2000)
        .call(() => {
          globalEvent.emit(GameEvent.NextLevel);
        });
    }
  }

  onDestroy() {
    super.onDestroy();
    Tween.removeTweens(this.right);
    this.A.off("globalpointermove", this.onAPointerMove, this);
  }

}
