import { renderTemplate } from "../constants.js";
import { ReglesOptionnelles } from "../settings/regles-optionnelles.js";
import { EffetsDraconiques } from "../tmr/effets-draconiques.js";
import { RdDTimestamp } from "../time/rdd-timestamp.js";

export class DialogRepos extends foundry.applications.api.DialogV2 {
  static async create(actor) {
    if (!actor.isPersonnage()) return
    if (!ReglesOptionnelles.isUsing("chateau-dormant-gardien") || !actor.isPersonnageJoueur()) {
      foundry.utils.mergeObject(actor.system.sommeil, {
        "nouveaujour": true,
        "insomnie": EffetsDraconiques.isSujetInsomnie(actor),
        "moral": "neutre",
        "heures": 4
      })
    }
    const hourDefs = RdDTimestamp.definitions()
    const heures = Math.max(1, actor.system.sommeil.heures ?? 4)
    const nuitHeureDebut = 7
    const nuitHeureFin = Math.min(11, Math.max(nuitHeureDebut, nuitHeureDebut + heures - 1))
    const nuitDuree = Math.max(1, nuitHeureFin - nuitHeureDebut + 1)
    const data = { name: actor.name, img: actor.img, system: actor.system, hourDefinitions: hourDefs, nuitHeureDebut, nuitHeureFin, nuitDuree }
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/dialog-repos.hbs", data)
    new DialogRepos(content, actor).render({ force: true })
  }

  constructor(content, actor) {
    super({
      title: "Se reposer",
      content,
      classes: ["dialog-repos"],
      position: { width: 400, height: 'fit-content' },
      buttons: [
        { label: "Se reposer", action: "repos", callback: () => this.repos() }
      ]
    })
    this.actor = actor
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    el.querySelectorAll(".sommeil-actor-moral a").forEach(a =>
      a.addEventListener("click", event => this.onActorMoral(event))
    )
    el.querySelectorAll('[name="sommeil.heure.debut"], [name="sommeil.heure.fin"]').forEach(input =>
      input.addEventListener("change", () => {
        const debut = Number.parseInt(el.querySelector('[name="sommeil.heure.debut"]')?.value ?? "0")
        const fin = Number.parseInt(el.querySelector('[name="sommeil.heure.fin"]')?.value ?? "0")
        const duree = el.querySelector('[name="sommeil.duree"]')
        if (duree) duree.textContent = Math.max(1, fin - debut + 1)
      })
    )
  }

  _val(sel) { return this.element.querySelector(sel)?.value ?? "" }

  async repos() {
    const selection = this._val("[name='repos']:checked")
    switch (selection) {
      case "sieste": return await this.sieste()
      case "nuit": return await this.nuit()
      case "chateau-dormant": return await this.chateauDormant()
      case "gris-reve": return await this.grisReve()
    }
  }

  async grisReve() {
    const el = this.element
    el.querySelector("[name='nb-jours']")?.dispatchEvent(new Event("change"))
    const nbJours = Number.parseInt(this._val("[name='nb-jours']"))
    await this.actor.grisReve(nbJours)
  }

  async chateauDormant() {
    await this.actor.dormirChateauDormant()
  }

  async nuit() {
    const el = this.element
    const debut = Number.parseInt(el.querySelector("[name='sommeil.heure.debut']")?.value ?? "0")
    const fin = Number.parseInt(el.querySelector("[name='sommeil.heure.fin']")?.value ?? "0")
    const sommeilHeures = Math.max(1, fin - debut + 1)
    await this.actor.update({ 'system.sommeil.heures': sommeilHeures })
    await this.actor.dormir(sommeilHeures, { chateauDormant: true })
  }

  async sieste() {
    const el = this.element
    el.querySelector("[name='sieste.heures']")?.dispatchEvent(new Event("change"))
    const siesteHeures = Number.parseInt(this._val("[name='sieste.heures']"))
    await this.actor.dormir(siesteHeures)
  }

  async onActorMoral(event) {
    const selected = event.currentTarget
    const parentDiv = selected.closest(".sommeil-actor-moral")
    const situationMoral = selected.dataset.moral
    await this.actor.setInfoSommeilMoral(situationMoral)
    const htmlMoral = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/sommeil/sommeil-actor-moral.hbs", { moral: situationMoral })
    if (parentDiv) parentDiv.innerHTML = htmlMoral
    parentDiv.querySelectorAll(".sommeil-actor-moral a").forEach(a =>
      a.addEventListener("click", event => this.onActorMoral(event))
    )
  }
}
