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

export class DialogChoixXpCarac extends foundry.applications.api.DialogV2 {
  static async choix(actor, xpData, caracs) {
    caracs = caracs.map(it => foundry.utils.mergeObject({ ajout: 0 }, it))
    xpData = foundry.utils.mergeObject({ reste: xpData.xpCarac }, xpData)
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-choix-xp-carac.hbs", {
      actor,
      caracDerivee: actor.findCaracByName(xpData.caracName),
      xpData,
      caracs
    })
    new DialogChoixXpCarac(content, actor, xpData, caracs).render({ force: true })
  }

  constructor(content, actor, xpData, caracs) {
    super({
      title: "Choisissez la répartition d'expérience",
      content,
      classes: ["rdd-dialog-select"],
      position: { width: 400, height: 'fit-content' },
      buttons: [
        { label: "Ajouter la répartition", action: "appliquer", icon: "fa-solid fa-check", callback: () => this.appliquerSelection() }
      ]
    })
    this.actor = actor
    this.xpData = xpData
    this.caracs = caracs
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    el.querySelectorAll("li.xpCarac-option .xpCarac-moins").forEach(btn =>
      btn.addEventListener("click", event => this.ajouterXp(event, -1))
    )
    el.querySelectorAll("li.xpCarac-option .xpCarac-plus").forEach(btn =>
      btn.addEventListener("click", event => this.ajouterXp(event, 1))
    )
  }

  ajouterXp(event, delta) {
    const liCarac = event.currentTarget.closest("li.xpCarac-option")
    const label = liCarac?.dataset?.caracLabel
    const carac = this.caracs.find(c => c.label == label)
    if (!carac) return
    if (carac.ajout + delta < 0) {
      ui.notifications.warn(`Impossible de diminuer les points à répartir en ${carac.label} en dessous de 0`)
      return
    }
    if (this.xpData.reste - delta < 0) {
      ui.notifications.warn(`Il ne reste plus de points à répartir en ${carac.label}`)
      return
    }
    carac.ajout += delta
    this.xpData.reste -= delta
    const ajoutInput = liCarac.querySelector("input.xpCarac-view-ajout")
    if (ajoutInput) ajoutInput.value = carac.ajout
    const resteInput = this.element.querySelector("input.xpCarac-reste")
    if (resteInput) resteInput.value = this.xpData.reste
  }

  async appliquerSelection() {
    if (this.xpData.reste > 0) {
      ui.notifications.warn(`Il vous reste ${this.xpData.reste} points à répartir`)
      return
    }
    this.caracs.filter(c => c.ajout > 0).forEach(c => {
      const xpData = { caracName: c.label, xpCarac: c.ajout }
      this.actor._xpCarac(xpData)
    })
    await super.close()
  }

  async close() {}

  _getHeaderButtons() { return [] }
}
