import { HIDE_DICE, renderTemplate, SHOW_DICE } from "./constants.js"
import { RdDUtility } from "./rdd-utility.js"

export class DialogValidationEncaissement extends foundry.applications.api.DialogV2 {
  static async validerEncaissement(actor, dmg, armure, onEncaisser) {
    const encaissement = await RdDUtility.jetEncaissement(actor, dmg, armure, { showDice: HIDE_DICE })
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-validation-encaissement.hbs", {
      actor,
      encaissement
    })
    new DialogValidationEncaissement(content, actor, dmg, armure, encaissement, onEncaisser).render({ force: true })
  }

  constructor(content, actor, dmg, armure, encaissement, onEncaisser) {
    super({
      title: "Validation d'encaissement",
      content,
      classes: ["rdd-roll-dialog"],
      position: { width: 350, height: 290 },
      buttons: [
        { label: "Valider", action: "valider", callback: () => this.onValider() },
        { label: "Annuler", action: "annuler", callback: () => {} }
      ]
    })
    this.actor = actor
    this.dmg = dmg
    this.armure = armure
    this.encaissement = encaissement
    this.onEncaisser = onEncaisser
    this.forceDiceResult = { total: encaissement.roll.result }
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelector("input.encaissement-roll-result")?.addEventListener("keyup", async event => {
      this.forceDiceResult.total = event.currentTarget.value
      this.encaissement = await RdDUtility.jetEncaissement(this.actor, this.dmg, this.armure, {
        showDice: HIDE_DICE,
        forceDiceResult: this.forceDiceResult
      })
      const totalEl = this.element.querySelector("label.encaissement-total")
      if (totalEl) totalEl.textContent = this.encaissement.total
      const blessEl = this.element.querySelector("label.encaissement-blessure")
      if (blessEl) blessEl.textContent = this.encaissement.blessures
    })
  }

  async onValider() {
    this.encaissement = await RdDUtility.jetEncaissement(this.actor, this.dmg, this.armure, {
      showDice: SHOW_DICE,
      forceDiceResult: this.forceDiceResult
    })
    this.onEncaisser(this.encaissement)
  }
}
