
export class DialogChoixXpCarac extends Dialog {

  static async choix(actor, xpData, caracs) {
    caracs = caracs.map(it => mergeObject({ ajout: 0 }, it))
    xpData = mergeObject({ reste: xpData.xpCarac }, xpData)
    const dialogData = {
      title: `Choisissez la répartition d'expérience`,
      content: await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-choix-xp-carac.hbs", {
        actor,
        caracDerivee: actor.findCaracByName(xpData.caracName),
        xpData,
        caracs
      }),
    }

    const dialogOptions = {
      classes: ["rdd-dialog-select"],
      width: 400,
      height: 'fit-content',
      'z-index': 99999
    }
    new DialogChoixXpCarac(dialogData, dialogOptions, actor, xpData, caracs).render(true)
  }

  constructor(dialogData, dialogOptions, actor, xpData, caracs) {
    dialogData = mergeObject(dialogData, {
      default: 'appliquer',
      buttons: {
        'appliquer': { icon:'<i class="fa-solid fa-check"></i>', label: "Ajouter la répartition", callback: it => this.appliquerSelection() }
      }
    })
    super(dialogData, dialogOptions)
    this.actor = actor
    this.xpData = xpData
    this.caracs = caracs
  }

  activateListeners(html) {
    //TODO
    super.activateListeners(html)
    this.html = html
    this.html.find("li.xpCarac-option .xpCarac-moins").click(event =>
      this.ajouterXp(event, -1)
    )
    this.html.find("li.xpCarac-option .xpCarac-plus").click(event =>
      this.ajouterXp(event, 1)
    )
  }

  async ajouterXp(event, delta) {
    const liCarac = this.html.find(event.currentTarget)?.parents("li.xpCarac-option")
    const label = liCarac?.data("carac-label")
    const carac = this.caracs.find(c => c.label == label)
    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
    liCarac.find("input.xpCarac-view-ajout").val(carac.ajout)
    this.html.find("input.xpCarac-reste").val(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 [] }
}