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

export class Level6 extends LevelBase {

  level: number = 6;

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

  right: Sprite;

  onLoad() {
    super.onLoad();

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

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

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

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

    const x = this.addChild(new Sprite(Assets.get(`level${this.level}/叉子.png`)))
    x.position.set(286, 1152);
    x.interactive = false;
    x.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 = null;
  pos = null;

  onAPointerUp(e) {
    this.pos = 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);

    this.check();
  }

  check() {

    const { x, y } = this.C;
    if (x >= 80 && x <= 230 && y >= 1030 && y <= 1100) {
      this.setTouchEnable(false);
      Tween.get(this.C)
        .to({ x: 129, y: 1049 }, 666, Ease.quadInOut);

      Tween.get(this.right)
        .wait(666)
        .to({ alpha: 1 }, 666, Ease.quadInOut)
        .wait(2000)
        .call(() => {
          globalEvent.emit(GameEvent.NextLevel);
        });
    }
  }

  onDestroy() {
    super.onDestroy();
    Tween.removeTweens(this.right);
    [this.A, this.B, this.C].forEach((item) => {
      item.off("globalpointermove", this.onAPointerMove, this);
    });
  }

}
