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

export class DialogSelect extends foundry.applications.api.DialogV2 {
  static extractIdNameImg(it) { return { id: it.id, name: it.name, img: it.img } }

  static async select(selectionData, onSelectChoice) {
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-select.hbs", selectionData)
    const dialog = new DialogSelect({
      title: selectionData.title ?? selectionData.label,
      content,
      selectionData,
      onSelectChoice
    })
    dialog.render({ force: true })
  }

  constructor({ title, content, selectionData, onSelectChoice }) {
    super({
      title,
      content,
      classes: ["rdd-dialog-select"],
      position: { width: 'fit-content' },
      buttons: [{ action: "close", label: "Fermer", icon: "fa-solid fa-xmark", callback: () => this.close() }]
    })
    this.selectionData = selectionData
    this.onSelectChoice = onSelectChoice
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelectorAll("li.select-choice").forEach(li => {
      li.addEventListener("click", () => this.choiceSelected(li.dataset.id))
    })
  }

  choiceSelected(selectedId) {
    const selected = this.selectionData.list.find(it => it.id == selectedId)
    this.close()
    if (selected) this.onSelectChoice(selected)
  }
}
