import { BatchedRenderer, QuarksLoader, QuarksUtil } from "three.quarks";
import { Object3D, Euler, Vector3 } from "three";
import { ResourcesC, UpdateController } from "@24tools/playable_template";
import { ThreeC } from "../ThreeC";
import { TimeC } from "../Timers/TimeC";
import { VFXType } from "../Enums/VFXType";
import { ResourcesType } from "../Presets/Enums/ResourcesType";

export class PropVfxC {
  static batchRenderer: BatchedRenderer;
  static loader: QuarksLoader;

  static Init() {
    this.batchRenderer = new BatchedRenderer();
    this.loader = new QuarksLoader();
    ThreeC.addToScene(this.batchRenderer);
    UpdateController.Instance.onUpdate.addDelegate(this.update.bind(this));
  }

  static Remove(vfx: Object3D) {
    vfx.removeFromParent();
    vfx.parent = null;
  }

  static update(delta: number) {
    delta *= TimeC.TimeScale;
    this.batchRenderer.update(delta);
  }

  static Play(
    type: VFXType | string,
    parent: Object3D | null = null,
    position: Vector3 | null = null,
    rotation: Euler | null = null,
    scale: Vector3 | null = null,
    odred: number | null = null,
  ) {
    const loaded = (ResourcesC.getResource(ResourcesType.VFX, type.toString()) as { obj: Object3D } | undefined)?.obj;
    if (!loaded) return new Object3D();

    const effect = loaded.clone(true) as Object3D;
    QuarksUtil.setAutoDestroy(effect, true);
    QuarksUtil.addToBatchRenderer(effect, this.batchRenderer);

    if (parent) parent.add(effect);
    else ThreeC.addToScene(effect);
    if (position) effect.position.copy(position);
    if (rotation) effect.rotation.copy(rotation);
    if (scale) effect.scale.copy(scale);
    if (odred) effect.renderOrder = odred;

    QuarksUtil.play(effect);
    return effect;
  }

  static StopEmision(effect: Object3D) {
    QuarksUtil.stop(effect);
  }

  static Restart(effect: Object3D) {
    QuarksUtil.play(effect);
  }

  static Pause(effect: Object3D) {
    QuarksUtil.pause(effect);
  }
}
