import { app } from "../../scripts/app.js";

app.registerExtension({
  name: "BooruGacha.CombineBans",

  async beforeRegisterNodeDef(nodeType, nodeData) {
    if (nodeData.name !== "BooruGachaCombineBans") return;

    const origCreated = nodeType.prototype.onNodeCreated;
    nodeType.prototype.onNodeCreated = function () {
      origCreated?.apply(this, arguments);

      this._bgInputCount = 0;

      this._bgAddBanInput();
      this._bgAddBanInput();

      this.addWidget("button", "bg_add_input", null, () => {
        this._bgAddBanInput();
        this._bgSaveCount();
        this._bgResize();
      }).label = "\u2795 Add Input";

      this.addWidget("button", "bg_rm_input", null, () => {
        this._bgRemoveLastBanInput();
      }).label = "\u2716 Remove Last";
    };

    nodeType.prototype._bgAddBanInput = function () {
      this._bgInputCount++;
      this.addInput(`bans_${this._bgInputCount}`, "BANLIST");
    };

    nodeType.prototype._bgRemoveLastBanInput = function () {
      for (let i = this.inputs.length - 1; i >= 0; i--) {
        if (this.inputs[i].name.startsWith("bans_")) {
          const count = this.inputs.filter((inp) =>
            inp.name.startsWith("bans_"),
          ).length;
          if (count <= 1) return;

          this.removeInput(i);
          this._bgInputCount = Math.max(1, this._bgInputCount - 1);

          let n = 0;
          for (let j = 0; j < this.inputs.length; j++) {
            if (this.inputs[j].name.startsWith("bans_")) {
              n++;
              this.inputs[j].name = `bans_${n}`;
            }
          }
          this._bgInputCount = n;
          this._bgSaveCount();
          this._bgResize();
          return;
        }
      }
    };

    nodeType.prototype._bgSaveCount = function () {
      if (!this.properties) this.properties = {};
      this.properties.bg_input_count = this._bgInputCount;
    };

    nodeType.prototype._bgResize = function () {
      const sz = this.computeSize();
      this.size[0] = Math.max(this.size[0], sz[0]);
      this.size[1] = Math.max(this.size[1], sz[1]);
      app.canvas?.setDirty(true, true);
    };

    const origConfigure = nodeType.prototype.onConfigure;
    nodeType.prototype.onConfigure = function (info) {
      origConfigure?.apply(this, arguments);

      const banInputs = (this.inputs || []).filter((inp) =>
        inp.name.startsWith("bans_"),
      );
      this._bgInputCount = banInputs.length;

      const saved = this.properties?.bg_input_count;
      if (saved && saved > this._bgInputCount) {
        for (let i = this._bgInputCount; i < saved; i++) {
          this._bgAddBanInput();
        }
      }
    };
  },
});
