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 Level9 extends LevelBase {

  level: number = 9;

  A: Sprite;

  right: Sprite;
  error: Sprite;

  onLoad() {
    super.onLoad();

    this.addChild(new Sprite(Assets.get(`level${this.level}/img.png`)))
      .position.set(46, 979);

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

    this.right = this.addChild(new Sprite(Assets.get(`common/right.png`)));
    this.right.position.set(470, 1050);
    this.right.alpha = 0;
    this.right.interactive = false;
    this.right.eventMode = "none";

    this.A.on("pointerdown", this.onAPointerDown, this);
    this.A.on("pointerup", this.onAPointerUp, this);
    this.A.on("globalpointermove", this.onAPointerMove, this);
  }

  pos = null;

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

  onAPointerDown(e) {
    const { x, y } = e.data.global;
    this.pos = {
      x: x - this.A.x,
      y: y - this.A.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.A.position.set(nx, ny);

    if (
      nx >= 110
      && nx <= 530
      && ny >= 980
      && ny <= 1100
    ) {
      this.setPauseCd(true);
      this.setTouchEnable(false);
      Tween.get(this.A)
        .to({ x: 380, y: 975 }, 444, Ease.quadInOut)
        .call(() => {
          Tween.get(this.right)
            .to({ alpha: 1 }, 444, Ease.quadInOut)
            .wait(2000)
            .call(() => {
              globalEvent.emit(GameEvent.NextLevel);
            });
        })

    }
  }

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

}
