import { ChatUtility } from "./chat-utility.js";
import { renderTemplate } from "./constants.js";
import { HtmlUtility } from "./html-utility.js";
import { RdDItemSigneDraconique } from "./item/signedraconique.js";
import { TMRUtility } from "./tmr-utility.js";

export class DialogCreateSigneDraconique extends foundry.applications.api.DialogV2 {
  static async createSigneForActors() {
    const signe = await RdDItemSigneDraconique.randomSigneDraconique({ ephemere: true });
    const dialogData = {
      signe,
      tmrs: TMRUtility.buildSelectionTypesTMR(signe.system.typesTMR),
      actors: game.actors.filter(actor => actor.isPersonnage() && actor.isHautRevant())
        .map(actor => ({ id: actor.id, name: actor.name, selected: false }))
    };
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-create-signedraconique.hbs", dialogData);
    new DialogCreateSigneDraconique(dialogData, content).render({ force: true })
  }

  constructor(dialogData, content) {
    super({
      title: "Créer un signe",
      content,
      classes: ["DialogCreateSigneDraconiqueActors"],
      position: { width: 500, height: 650 },
      buttons: [
        { label: "Ajouter aux haut-rêvants", action: "ajouter", callback: () => this._onCreerSigneActeurs() }
      ]
    })
    this.dialogData = dialogData
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    this.setEphemere(this.dialogData.signe.system.ephemere)
    el.querySelector(".signe-aleatoire")?.addEventListener("click", () => this.setSigneAleatoire())
    el.querySelector("[name='signe.system.ephemere']")?.addEventListener("change", event => this.setEphemere(event.currentTarget.checked))
    el.querySelector(".signe-xp-sort")?.addEventListener("change", event => this.onValeurXpSort(event))
    el.querySelectorAll("input.select-actor").forEach(i => i.addEventListener("change", event => this.onSelectActor(event)))
    el.querySelectorAll("input.select-tmr").forEach(i => i.addEventListener("change", event => this.onSelectTmr(event)))
  }

  async _onCreerSigneActeurs() {
    const el = this.element
    el.querySelector("[name='signe.system.ephemere']")?.dispatchEvent(new Event("change"))
    el.querySelector(".signe-xp-sort")?.dispatchEvent(new Event("change"))
    this.validerSigne()
    await Promise.all(this.dialogData.actors.filter(it => it.selected)
      .map(it => game.actors.get(it.id))
      .map(async actor => await this._createSigneForActor(actor, this.dialogData.signe)))
  }

  async _createSigneForActor(actor, signe) {
    await actor.createEmbeddedDocuments("Item", [signe])
    await ChatMessage.create({
      whisper: ChatUtility.getOwners(actor),
      content: await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/chat-signe-draconique-actor.hbs", {
        signe,
        alias: actor.getAlias()
      })
    })
  }

  validerSigne() {
    const el = this.element
    const v = sel => el.querySelector(sel)?.value ?? ""
    this.dialogData.signe.name = v("[name='signe.name']")
    this.dialogData.signe.system.valeur.norm = v("[name='signe.system.valeur.norm']")
    this.dialogData.signe.system.valeur.sign = v("[name='signe.system.valeur.sign']")
    this.dialogData.signe.system.valeur.part = v("[name='signe.system.valeur.part']")
    this.dialogData.signe.system.difficulte = v("[name='signe.system.difficulte']")
    this.dialogData.signe.system.ephemere = el.querySelector("[name='signe.system.ephemere']")?.checked ?? false
    this.dialogData.signe.system.duree = v("[name='signe.system.duree']")
    this.dialogData.signe.system.typesTMR = TMRUtility.buildListTypesTMRSelection(this.dialogData.tmrs)
  }

  async setSigneAleatoire() {
    const newSigne = await RdDItemSigneDraconique.randomSigneDraconique({ ephemere: true })
    const el = this.element
    const setVal = (sel, val) => { const i = el.querySelector(sel); if (i) i.value = val }
    setVal("[name='signe.name']", newSigne.name)
    setVal("[name='signe.system.valeur.norm']", newSigne.system.valeur.norm)
    setVal("[name='signe.system.valeur.sign']", newSigne.system.valeur.sign)
    setVal("[name='signe.system.valeur.part']", newSigne.system.valeur.part)
    setVal("[name='signe.system.difficulte']", newSigne.system.difficulte)
    setVal("[name='signe.system.duree']", newSigne.system.duree)
    const ephemereEl = el.querySelector("[name='signe.system.ephemere']")
    if (ephemereEl) ephemereEl.checked = newSigne.system.ephemere
    this.dialogData.tmrs = TMRUtility.buildSelectionTypesTMR(newSigne.system.typesTMR)
    this.dialogData.tmrs.forEach(it => {
      const tmrEl = el.querySelector(`[data-tmr-name='${it.name}']`)
      if (tmrEl) tmrEl.checked = it.selected
    })
    this.setEphemere(newSigne.system.ephemere)
  }

  async setEphemere(ephemere) {
    this.dialogData.signe.system.ephemere = ephemere
    const dureeEl = this.element.querySelector(".signe-system-duree")
    if (dureeEl) HtmlUtility.showControlWhen(dureeEl, ephemere)
  }

  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
  }

  onSelectTmr(event) {
    const tmrName = event.currentTarget?.dataset?.tmrName
    const onTmr = this.dialogData.tmrs.find(it => it.name == tmrName)
    if (onTmr) onTmr.selected = event.currentTarget.checked
  }

  onValeurXpSort(event) {
    const codeReussite = event.currentTarget.attributes['data-typereussite']?.value ?? 0
    const xp = Number(event.currentTarget.value)
    const oldValeur = this.dialogData.signe.system.valeur
    this.dialogData.signe.system.valeur = RdDItemSigneDraconique.calculValeursXpSort(codeReussite, xp, oldValeur)
  }
}
