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

export class RdDEncaisser extends foundry.applications.api.DialogV2 {
  static async encaisser(actor) {
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-roll-encaisser.hbs",
      { ajustementsEncaissement: RdDUtility.getAjustementsEncaissement() }
    )
    new RdDEncaisser(content, actor).render({ force: true })
  }

  constructor(content, actor) {
    if (actor.isEntiteNonIncarnee()) {
      throw `${actor.name} est une entité non incarnée et ne peut pas subnir de dommages`
    }
    const buttons = [
      { label: "Mortel", action: RDD_CONFIG.encaissement.mortel, callback: () => this.performEncaisser(RDD_CONFIG.encaissement.mortel) }
    ]
    if (!actor.isEntite()) {
      buttons.push(
        { label: "Non-mortel", action: RDD_CONFIG.encaissement.nonmortel, callback: () => this.performEncaisser(RDD_CONFIG.encaissement.nonmortel) },
        { label: "Sonné", action: "sonne", callback: () => this.actor.setSonne() }
      )
    }
    super({
      title: "Jet d'Encaissement",
      content,
      buttons,
      classes: ["rdd-roll-dialog"],
      position: { width: 320, height: 'fit-content' }
    })
    this.actor = actor
    this.modifier = 0
    this.encaisserSpecial = "aucun"
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    const modInput = el.querySelector('[name="modificateurDegats"]')
    if (modInput) {
      modInput.value = "0"
      modInput.addEventListener("change", event => { this.modifier = event.currentTarget.value })
    }
    el.querySelector('[name="encaisserSpecial"]')?.addEventListener("change", event => {
      this.encaisserSpecial = event.currentTarget.value
    })
  }

  performEncaisser(mortalite) {
    this.actor.encaisserDommages({
      total: Number(this.modifier),
      ajustement: Number(this.modifier),
      encaisserSpecial: this.encaisserSpecial,
      mortalite: mortalite,
      penetration: 0
    })
  }
}
