import { BatchedRenderer, QuarksLoader, QuarksUtil } from "three.quarks";
import { Object3D, Euler, Vector3 } from "three";
import { ResourcesC } from "@hitplay/playable_template";
import { ThreeC } from "../../controllers/ThreeC";
import { GameLoop } from "../../core/GameLoop";

// Resource "type" under which Quark VFX JSONs are registered (see resources.ts).
const VFX_RESOURCE_TYPE = "vfx_json";

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

  static init() {
    this.batchRenderer = new BatchedRenderer();
    this.loader = new QuarksLoader();
    ThreeC.addToScene(this.batchRenderer);
    GameLoop.register(this.update.bind(this));
  }

  static update(delta: number) {
    this.batchRenderer.update(delta);
  }

  static Play(
    name: string,
    parent: Object3D | null = null,
    position: Vector3 | null = null,
    rotation: Euler | null = null,
    scale: Vector3 | null = null,
    renderOrder: number | null = null,
  ): Object3D {
    const resource = ResourcesC.getResource<{ obj: Object3D } | undefined>(
      VFX_RESOURCE_TYPE,
      name,
    );
    if (!resource?.obj) return new Object3D();

    const effect = resource.obj.clone(true);
    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 (renderOrder != null) effect.renderOrder = renderOrder;

    return effect;
  }
}
