import { MaleficesUtility } from "./malefices-utility.js";

export class MaleficesRollDialog {

  /* -------------------------------------------- */
  static async create(actor, rollData) {
    const isCard = rollData?.attr?.iscard
    const template = isCard
      ? 'systems/fvtt-malefices/templates/dialogs/confrontation-dialog.hbs'
      : 'systems/fvtt-malefices/templates/dialogs/roll-dialog-generic.hbs'

    const content = await foundry.applications.handlebars.renderTemplate(template, rollData)

    return foundry.applications.api.DialogV2.wait({
      window: {
        title: isCard ? "Tirage" : "Jet de dé",
        icon: isCard ? "fa-solid fa-layer-group" : "fa-solid fa-dice-d20",
      },
      classes: ["malefices-roll-dialog"],
      position: { width: 540 },
      modal: false,
      rejectClose: false,
      content,
      buttons: [
        {
          action: "roll",
          label: isCard ? "Tirer une carte" : "Lancer le dé",
          icon: isCard ? "fa-solid fa-layer-group" : "fa-solid fa-check",
          default: true,
          callback: (event, button, dialog) => {
            MaleficesRollDialog._updateRollDataFromForm(rollData, button.form.elements)
            if (isCard) {
              MaleficesUtility.tirageConfrontationMalefices(rollData)
            } else {
              MaleficesUtility.rollMalefices(rollData)
            }
          }
        },
        {
          action: "cancel",
          label: "Annuler",
          icon: "fa-solid fa-times",
        }
      ],
    })
  }

  /* -------------------------------------------- */
  static _updateRollDataFromForm(rollData, elements) {
    if (elements.bonusMalusPerso)     rollData.bonusMalusPerso     = Number(elements.bonusMalusPerso.value)
    if (elements.bonusMalusSituation) rollData.bonusMalusSituation = Number(elements.bonusMalusSituation.value)
    if (elements.bonusMalusDef)       rollData.bonusMalusDef       = Number(elements.bonusMalusDef.value)
    if (elements.bonusMalusPortee)    rollData.bonusMalusPortee    = Number(elements.bonusMalusPortee.value)
    if (elements.confrontationDegre)  rollData.confrontationDegre  = Number(elements.confrontationDegre.value)
    if (elements.confrontationModif)  rollData.confrontationModif  = Number(elements.confrontationModif.value)
  }
}