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";
import { getApp } from "@/pages/GamePage/GamePage.tsx";

export class Level7 extends LevelBase {

  level: number = 7;

  pig: Sprite;

  coin: Sprite;

  onLoad() {
    super.onLoad();

    this.pig = this.addChild(new Sprite(Assets.get("level7/pig.png")));
    this.pig.anchor.set(0.5);
    this.pig.position.set(380, 900);

    this.coin = this.pig.addChild(new Sprite(Assets.get("level7/金币.png")));
    this.coin.anchor.set(0.5);
    this.coin.position.set(12, 35);

    this.pig.addChild(new Sprite(Assets.get("level7/mask.png")))
      .position.set(-203, -108);

    getApp().stage.on("pointerdown", this.onPointerDown, this);
    getApp().stage.on("pointerup", this.onPointerUp, this);
    getApp().stage.on("pointermove",  this.onPointerMove, this);

  }

  passLevel() {
    this.setPauseCd(true);
    this.setTouchEnable(false);
    getApp().stage.off("pointerdown", this.onPointerDown, this);
    getApp().stage.off("pointerup", this.onPointerUp, this);
    getApp().stage.off("pointermove",  this.onPointerMove, this);
    Tween.get(this.pig)
      .to({ angle: -180, }, 222)
      .call(() => {
        Tween.get(this.coin)
          .to({ y: -300, }, 666, Ease.quadInOut)
          .wait(2000)
          .call(() => {
            globalEvent.emit(GameEvent.NextLevel);
          });
      });
  }

  calcAngle(x: number, y: number) {
    const centerX = 378;
    const centerY = 812;
    const dx = x - centerX;
    const dy = y - centerY;
    return Math.atan2(dy, dx) * (180 / Math.PI);
  }

  sAngle = null;

  onPointerUp(e) {
    this.sAngle = null;
  }

  onPointerMove = (e: any) => {
    if (this.sAngle === null) return;
    const { x, y } = e.data.global;
    const angle = this.calcAngle(x, y);
    this.pig.angle = angle - this.sAngle;

    const pAngle = this.pig.angle % 360;

    if (
      (pAngle < -150 && pAngle > -200)
      || (pAngle > 160 && pAngle < 210)
    ) {
      this.passLevel();
    }
  };

  onPointerDown(e) {
    const { x: sx, y: sy } = e.data.global;
    this.sAngle = this.calcAngle(sx, sy) - this.pig.angle;
  }

  onDestroy() {
    super.onDestroy();
    Tween.removeTweens(this.pig);
    Tween.removeTweens(this.coin);
    getApp().stage.off("pointerdown", this.onPointerDown, this);
    getApp().stage.off("pointerup", this.onPointerUp, this);
    getApp().stage.off("pointermove",  this.onPointerMove, this);
  }

}
