import { renderTemplate } from "./constants.js";

export class DialogSplitItem extends foundry.applications.api.DialogV2 {
  static async create(item, callback) {
    const splitData = {
      item: item,
      choix: { quantite: 1, max: item.system.quantite - 1 }
    }
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-item-split.hbs", splitData)
    return new DialogSplitItem(item, splitData, content, callback)
  }

  constructor(item, splitData, content, callback) {
    super({
      title: "Séparer en deux",
      content,
      classes: ["dialogsplit"],
      position: { width: 300, height: 'fit-content' },
      buttons: [
        { label: "Séparer", action: "separer", callback: () => this.onSplit() }
      ]
    })
    this.callback = callback
    this.item = item
    this.splitData = splitData
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelector(".choix-quantite")?.addEventListener("change", event => {
      this.splitData.choix.quantite = Number(event.currentTarget.value)
    })
  }

  async onSplit() {
    const input = this.element.querySelector(".choix-quantite")
    if (input) {
      input.dispatchEvent(new Event("change"))
    }
    this.callback(this.item, this.splitData.choix.quantite)
  }
}
