import { Assets, Container, PointData, Sprite } from "pixi.js";
import { Ele, EleConfig } from "@/pages/GamePage/config/Config.ts";
import { Body } from "detect-collisions";
import { BodyProps } from "detect-collisions/dist/model";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";
import { Tween } from "@/pages/GamePage/tween";

export abstract class Element extends Container {

  id: Ele = null;
  sp: Sprite = null;

  body: Body = null;

  canEat: boolean = true;

  abstract initUI(): void;
  abstract initPhy(): void;

  abstract updatePhy(): void;

  init(): void {
    const {texture} = EleConfig[this.id];

    this.sp = this.addChild(new Sprite(Assets.get(texture)));
    this.sp.anchor.set(0.5);

    this.sp.angle = Math.random() * 360;

    this.initUI();
    this.initPhy();

    this.scaleX = 0;
    this.scaleY = 0;
    this.body.setScale(this.scaleX, this.scaleY);
    this.updatePhy();

    Tween.get(this, {
      onChange: () => {
        this.body.setScale(this.scaleX, this.scaleY);
        this.updatePhy();
      }
    }).to({ scaleX: 1, scaleY: 1 }, 333);
  }

  onDestroy(): void {

  }


  get scaleX() {
    return this.sp.scale.x;
  }

  set scaleX(value: number) {
    this.sp.scale.x = value;
  }

  get scaleY() {
    return this.sp.scale.y;
  }

  set scaleY(value: number) {
    this.sp.scale.y = value;
  }


  beEaten(pos: PointData) {
    if (!this.canEat) return;
    this.canEat = false;

    collisionSys.remove(this.body);
    this.body = null;

    Tween.removeTweens(this);
    Tween.get(this)
      .to({
        x: pos.x, y: pos.y,
        scaleX: 0.1, scaleY: 0.1,
      }, 444)
      .call(() => {
        this.onDestroy();
        this.removeFromParent();
      });
  }

}
