import { UpdateController } from "@24tools/playable_template";
import { PropC } from "./PropC";
import { PropHpBar } from "./PropHpBar";

/** TODO: set false after HP bar position tuning */
const DEBUG_ALWAYS_VISIBLE_HP_BARS = false;

export class PropHpUIC {
  private static inited = false;
  private static root: HTMLElement | null = null;
  private static bars = new Map<PropC, PropHpBar>();

  static init() {
    if (this.inited) return;
    this.inited = true;

    const uiRoot = document.getElementById("ui");
    if (!uiRoot) return;

    this.root = document.createElement("div");
    this.root.id = "prop-hp-layer";
    this.root.className = "prop-hp-layer";
    uiRoot.appendChild(this.root);

    UpdateController.Instance.onUpdate.addDelegate((delta) => {
      for (const bar of this.bars.values()) {
        bar.update(delta);
      }
    });
  }

  static createBar(prop: PropC): PropHpBar | undefined {
    if (!this.root || this.bars.has(prop)) return this.bars.get(prop);

    const bar = new PropHpBar(prop, this.root);
    this.bars.set(prop, bar);

    if (DEBUG_ALWAYS_VISIBLE_HP_BARS) {
      bar.setVisible(true);
    }

    return bar;
  }

  static showFor(props: PropC[]) {
    if (DEBUG_ALWAYS_VISIBLE_HP_BARS) {
      this.showAll();
      return;
    }

    for (const bar of this.bars.values()) {
      bar.setVisible(false);
    }

    for (const prop of props) {
      if (prop.isBroken) continue;
      this.bars.get(prop)?.setVisible(true);
    }
  }

  static hideAll() {
    if (DEBUG_ALWAYS_VISIBLE_HP_BARS) return;

    for (const bar of this.bars.values()) {
      bar.setVisible(false);
    }
  }

  private static showAll() {
    for (const [prop, bar] of this.bars) {
      bar.setVisible(!prop.isBroken);
    }
  }

  static removeBar(prop: PropC) {
    const bar = this.bars.get(prop);
    if (!bar) return;

    bar.destroy();
    this.bars.delete(prop);
  }
}
