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

  level: number = 18;

  cloud1: Sprite;
  cloud2: Sprite;
  ice: Sprite;
  ice2: Sprite;

  right: Sprite;

  onLoad() {
    super.onLoad();

    this.addChild(new Sprite(Assets.get(`level18/sun.png`)))
      .position.set(267, 703);

    this.cloud2 = this.addChild(new Sprite(Assets.get(`level18/cloud2.png`)));
    this.cloud2.position.set(45, 743);

    this.cloud1 = this.addChild(new Sprite(Assets.get(`level18/cloud1.png`)));
    this.cloud1.position.set(176, 664);

    this.ice = this.addChild(new Sprite(Assets.get(`level18/ice.png`)));
    this.ice.position.set(259, 1031);

    this.ice2 = this.addChild(new Sprite(Assets.get(`level18/ice2.png`)));
    this.ice2.position.set(148, 1100);

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

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

    this.cloud2.on("pointerdown", this.onAPointerDown, this);
    this.cloud2.on("pointerup", this.onAPointerUp, this);
    this.cloud2.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: c1x, y: c1y } = this.cloud1;
    const { x: c2x, y: c2y } = this.cloud2;

    if (
      (c1x < -125 || c1x > 350 || c1y < 595 || c1y > 820)
      && (c2x < -125 || c2x > 350 || c2y < 595 || c2y > 820)
    ) {
      this.setPauseCd(true);
      this.setTouchEnable(false);
      Tween.get(this.ice).to({ alpha: 0 }, 666, Ease.quadInOut);
      Tween.get(this.ice2).wait(444).to({ alpha: 1 }, 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.ice);
    Tween.removeTweens(this.ice2);
    Tween.removeTweens(this.right);
    this.cloud1.off("globalpointermove", this.onAPointerMove, this);
    this.cloud2.off("globalpointermove", this.onAPointerMove, this);
  }

}
