import { EcrymeUtility } from "../common/ecryme-utility.js";

const { HandlebarsApplicationMixin } = foundry.applications.api

/**
 * Roll dialog — Application V2 version.
 * Reads all form values at roll time (no live tracking needed).
 */
export class EcrymeRollDialog extends HandlebarsApplicationMixin(foundry.applications.api.ApplicationV2) {

  /** @override */
  static DEFAULT_OPTIONS = {
    classes: ["fvtt-ecryme", "ecryme-roll-dialog"],
    position: { width: 540 },
    window: { title: "ECRY.ui.rolltitle" },
    actions: {
      roll:   EcrymeRollDialog.#onRoll,
      cancel: EcrymeRollDialog.#onCancel,
    },
  }

  /** @override */
  static PARTS = {
    content: { template: "systems/fvtt-ecryme/templates/dialogs/roll-dialog-generic.hbs" },
  }

  /* -------------------------------------------- */
  constructor(actor, rollData, options = {}) {
    super(options)
    this.actor    = actor
    this.rollData = rollData
  }

  /* -------------------------------------------- */
  static async create(actor, rollData) {
    return new EcrymeRollDialog(actor, rollData)
  }

  /* -------------------------------------------- */
  async _prepareContext() {
    return {
      ...this.rollData,
      config: game.ecryme.config,
    }
  }

  /* -------------------------------------------- */
  /** Read all form values at roll time, then execute. */
  static #onRoll(event, target) {
    const el = this.element

    const bonusEl      = el.querySelector('#bonusMalusPerso')
    const diffEl       = el.querySelector('#roll-difficulty')
    const specEl       = el.querySelector('#roll-specialization')
    const traitBonusEl = el.querySelector('#roll-trait-bonus')
    const traitMalusEl = el.querySelector('#roll-trait-malus')
    const transcEl     = el.querySelector('#roll-select-transcendence')
    const spleenEl     = el.querySelector('#roll-use-spleen')
    const idealEl      = el.querySelector('#roll-use-ideal')

    if (bonusEl)      this.rollData.bonusMalusPerso    = Number(bonusEl.value)
    if (diffEl)       this.rollData.difficulty         = Number(diffEl.value) || 0
    if (specEl)       this.rollData.selectedSpecs      = Array.from(specEl.selectedOptions).map(o => o.value)
    if (traitBonusEl) this.rollData.traitsBonus        = Array.from(traitBonusEl.selectedOptions).map(o => o.value)
    if (traitMalusEl) this.rollData.traitsMalus        = Array.from(traitMalusEl.selectedOptions).map(o => o.value)
    if (transcEl)     this.rollData.skillTranscendence = Number(transcEl.value)
    if (spleenEl)     this.rollData.useSpleen          = spleenEl.checked
    if (idealEl)      this.rollData.useIdeal           = idealEl.checked

    EcrymeUtility.rollEcryme(this.rollData)
    this.close()
  }

  /* -------------------------------------------- */
  static #onCancel(event, target) {
    this.close()
  }
}
