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

export class DialogChateauDormant extends foundry.applications.api.DialogV2 {
  static async create() {
    const date = game.system.rdd.calendrier.dateCourante()
    const dialogData = {
      actors: game.actors.filter(actor => actor.isPersonnageJoueur()),
      date,
      motifStress: `Nuit du ${date}`,
      finChateauDormant: game.system.rdd.calendrier.getTimestampFinChateauDormant()
    }
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/dialog-chateau-dormant.hbs", dialogData)
    new DialogChateauDormant(dialogData, content).render({ force: true })
  }

  constructor(dialogData, content) {
    super({
      title: "De Chateau dormant à Vaisseau",
      content,
      classes: ["rdd-dialog-chateau-dormant"],
      position: { width: 600, height: 'fit-content' },
      buttons: [
        { label: "Passer à Vaisseau!", action: "chateauDormant", callback: () => this.onChateauDormant() }
      ]
    })
    this.dialogData = dialogData
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelectorAll("input.sommeil-insomnie").forEach(el =>
      el.addEventListener("change", event => this.onInsomnie(event))
    )
    this._activateListenerOnActorMoral(this.element)
  }

  _activateListenerOnActorMoral(el) {
    el.querySelectorAll("span.sommeil-actor-moral a").forEach(a =>
      a.addEventListener("click", event => this.onActorMoral(event))
    )
  }

  onInsomnie(event) {
    const cb = event.currentTarget
    const isInsomnie = cb.checked
    const actorRow = cb.closest(".set-sommeil-actor")
    const heures = actorRow?.querySelector("input.sommeil-heures")
    if (heures) {
      heures.disabled = isInsomnie
      if (isInsomnie) heures.value = "0"
    }
  }

  async onActorMoral(event) {
    const selected = event.currentTarget
    const actorRow = selected.closest(".set-sommeil-actor")
    const actorId = actorRow?.dataset?.actorId
    const actor = this.getActor(actorId)
    if (!actor) return
    actor.system.sommeil.moral = selected.dataset.moral
    const htmlMoral = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/sommeil-actor-moral.hbs", actor.system.sommeil)
    const moralEl = actorRow.querySelector(".sommeil-actor-moral")
    if (moralEl) moralEl.innerHTML = htmlMoral
    this._activateListenerOnActorMoral(actorRow)
  }

  getActor(actorId) {
    return this.dialogData.actors.find(it => it.id == actorId)
  }

  async onChateauDormant() {
    const el = this.element
    const motifStress = el.querySelector("form input[name='motifStress']")?.value ?? ""
    Array.from(el.querySelectorAll("li.set-sommeil-actor")).forEach(row => {
      const consigne = this.extractConsigneActor(row, motifStress)
      if (consigne) consigne.actor.prepareChateauDormant(consigne)
    })
  }

  extractConsigneActor(actorRow, motifStress) {
    const actorId = actorRow.dataset?.actorId
    const actor = this.getActor(actorId)
    if (!actor) return null
    const insomnie = actorRow.querySelector("input.sommeil-insomnie")?.checked ?? false
    return {
      actor,
      ignorer: actorRow.querySelector("input.sommeil-ignorer")?.checked ?? false,
      stress: {
        motif: motifStress,
        valeur: Number.parseInt(actorRow.querySelector("input.sommeil-stress")?.value ?? "0"),
      },
      sommeil: {
        nouveaujour: true,
        date: this.dialogData.finChateauDormant,
        insomnie,
        heures: insomnie ? 0 : Number.parseInt(actorRow.querySelector("input.sommeil-heures")?.value ?? "0"),
        moral: actor.system.sommeil.moral ?? "neutre",
      }
    }
  }
}
