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

export class Level21 extends LevelBase {

  level: number = 21;

  A: Sprite;
  B: Sprite;

  right: Sprite;

  onLoad() {
    super.onLoad();

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

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

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

    [this.A, this.B].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: ax, y: ay, width: aw, height: ah } = this.A;
    const { x: bx, y: by, width: bw, height: bh } = this.B;

    const edge = 20;
    const isIns = new Rectangle(ax + edge, ay + edge, aw - edge * 2, ah - edge * 2)
      .intersects(new Rectangle(bx + edge, by + edge, bw - edge * 2, bh - edge * 2));

    if (isIns) {
      this.setPauseCd(true);
      this.setTouchEnable(false);
      this.right.position.set(bx - 30, by - 30);
      Tween.get(this.B).to({ alpha: 0 }, 666, Ease.quadInOut);
      Tween.get(this.right)
        .to({ alpha: 1 }, 666, Ease.quadInOut)
        .wait(2000)
        .call(() => {
          globalEvent.emit(GameEvent.NextLevel);
        });
    }

  }

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

}
