import { WastelandUtility } from "../wasteland-utility.js"

/**
 * Dialogue de jet de dé pour Wasteland - Version DialogV2
 */
export class WastelandRollDialog {

  /**
   * Create and display the roll dialog
   * @param {WastelandActor} actor - The actor making the roll
   * @param {Object} rollData - Data for the roll
   * @returns {Promise<WastelandRollDialog>}
   */
  static async create(actor, rollData) {
    // Préparer le contexte pour le template
    const context = {
      ...rollData,
      difficulte: String(rollData.difficulte || 0),
      img: actor.img,
      name: actor.name,
      config: game.system.wasteland.config,
    }

    // Rendre le template en HTML
    const content = await foundry.applications.handlebars.renderTemplate(
      "systems/fvtt-wasteland/templates/roll-dialog-v2.hbs",
      context
    )

    // Utiliser DialogV2.wait avec le HTML rendu
    return foundry.applications.api.DialogV2.wait({
      window: { title: "Test de Capacité", icon: "fa-solid fa-dice-d20" },
      classes: ["wasteland-roll-dialog"],
      position: { width: 500 },
      modal: false,
      content,
      buttons: rollData.charme ? [
        {
          action: "roll",
          label: "Lancer",
          icon: "fa-solid fa-dice-d20",
          default: true,
          callback: (event, button, dialog) => {
            this._updateRollDataFromForm(rollData, button.form.elements, actor)
            WastelandUtility.rollWasteland(rollData)
          }
        }
      ] : [
        {
          action: "rolld10",
          label: "Lancer 1d10",
          icon: "fa-solid fa-dice-d10",
          default: true,
          callback: (event, button, dialog) => {
            this._updateRollDataFromForm(rollData, button.form.elements, actor)
            rollData.mainDice = "1d10"
            WastelandUtility.rollWasteland(rollData)
          }
        },
        {
          action: "rolld20",
          label: "Lancer 1d20",
          icon: "fa-solid fa-dice-d20",
          callback: (event, button, dialog) => {
            this._updateRollDataFromForm(rollData, button.form.elements, actor)
            rollData.mainDice = "1d20"
            WastelandUtility.rollWasteland(rollData)
          }
        },
      ],
      rejectClose: false,
    })
  }

  /**
   * Mettre à jour rollData avec les valeurs du formulaire
   * @param {Object} rollData - L'objet rollData à mettre à jour
   * @param {HTMLFormControlsCollection} formElements - Les éléments du formulaire
   * @param {WastelandActor} actor - L'acteur pour récupérer les attributs
   * @private
   */
  static _updateRollDataFromForm(rollData, formElements, actor) {
    // Attributs
    if (formElements.attrKey) {
      rollData.attrKey = formElements.attrKey.value
      if (rollData.attrKey !== "tochoose" && actor) {
        rollData.attr = foundry.utils.duplicate(actor.system.attributs[rollData.attrKey])
      }
    }

    // Modificateurs de base
    if (formElements.difficulte) {
      rollData.difficulte = Number(formElements.difficulte.value)
    }
    if (formElements.modificateur) {
      rollData.modificateur = Number(formElements.modificateur.value)
    }

    // Charme
    if (formElements.charmeDice) {
      rollData.charmeDice = String(formElements.charmeDice.value)
    }

    // Combat mêlée
    if (formElements.typeAttaque) {
      rollData.typeAttaque = String(formElements.typeAttaque.value)
      rollData.typeAttaqueLabel = rollData.config.attaques[rollData.typeAttaque]
    }
    if (formElements.isMonte !== undefined) {
      rollData.isMonte = formElements.isMonte.checked
    }

    // Combat distance
    if (formElements.visee !== undefined) {
      rollData.visee = formElements.visee.checked
    }
    if (formElements.cibleconsciente !== undefined) {
      rollData.cibleconsciente = formElements.cibleconsciente.checked
    }
    if (formElements.ciblecourt !== undefined) {
      rollData.ciblecourt = formElements.ciblecourt.checked
    }
    if (formElements.typeCouvert) {
      rollData.typeCouvert = String(formElements.typeCouvert.value)
      const couvert = rollData.config.couverts[rollData.typeCouvert]
      if (rollData.typeCouvert !== "aucun" && couvert) {
        rollData.typeCouvertLabel = couvert.name
        rollData.typeCouvertValue = couvert.value
      }
    }

    // Désavantages (avantages tactiques)
    if (!rollData.desavantages) rollData.desavantages = {}
    
    if (formElements.cibleausol !== undefined) {
      rollData.desavantages.cibleausol = formElements.cibleausol.checked
    }
    if (formElements.cibledesarmee !== undefined) {
      rollData.desavantages.cibledesarmee = formElements.cibledesarmee.checked
    }
    if (formElements.ciblerestreint !== undefined) {
      rollData.desavantages.ciblerestreint = formElements.ciblerestreint.checked
    }
    if (formElements.cibleimmobilisée !== undefined) {
      rollData.desavantages.cibleimmobilisée = formElements.cibleimmobilisée.checked
    }
    if (formElements.ciblesurplomb !== undefined) {
      rollData.desavantages.ciblesurplomb = formElements.ciblesurplomb.checked
    }

    // Double D20
    if (formElements.doubleD20 !== undefined) {
      rollData.doubleD20 = formElements.doubleD20.checked
    }
  }
}
