import { renderTemplate } from "../constants.js";

export class DialogStress extends foundry.applications.api.DialogV2 {
  static async distribuerStress() {
    const dialogData = {
      motif: "Motif",
      stress: 10,
      immediat: false,
      actors: game.actors.filter(actor => actor.isPersonnageJoueur())
        .map(actor => ({ id: actor.id, name: actor.name, selected: true }))
    }
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/dialog-stress.hbs", dialogData)
    new DialogStress(dialogData, content).render({ force: true })
  }

  constructor(dialogData, content) {
    super({
      title: "Donner du stress",
      content,
      window: { frame: true, positioned: true },
      classes: ["DialogStress"],
      position: { width: 400 },
      buttons: [
        { label: "Stress !", action: "stress", callback: () => this.onStress() }
      ]
    })
    this.dialogData = dialogData
  }

  _onRender(context, options) {
    super._onRender(context, options)
    this.element.querySelectorAll("input.select-actor").forEach(el =>
      el.addEventListener("change", event => this.onSelectActor(event))
    )
  }

  async onStress() {
    const el = this.element
    const motif = el.querySelector("form.rdddialogstress input[name='motif']")?.value ?? ""
    const stress = Number(el.querySelector("form.rdddialogstress input[name='stress']")?.value ?? 0)
    const immediat = el.querySelector("form.rdddialogstress input[name='immediat']")?.checked ?? false
    const compteur = immediat ? "experience" : "stress"

    await Promise.all(
      this.dialogData.actors.filter(it => it.selected)
        .map(actor => game.actors.get(actor.id))
        .filter(actor => actor != undefined)
        .map(actor => actor.distribuerStress(compteur, stress, motif))
    )
  }

  onSelectActor(event) {
    const actorId = event.currentTarget?.dataset?.actorId
    const actor = this.dialogData.actors.find(it => it.id == actorId)
    if (actor) actor.selected = event.currentTarget.checked
  }
}
