import { RdDTimestamp } from "./rdd-timestamp.js";

export class RdDCalendrierEditor extends foundry.applications.api.DialogV2 {
  constructor(html, calendrier, calendrierData) {
    super({
      title: "Editeur de date/heure",
      content: html,
      classes: ["rdd-dialog-calendar-editor"],
      window: { frame: true, positioned: true },
      position: { width: 400 },
      buttons: [
        { label: "Enregistrer", action: "save", callback: () => this.saveCalendrier() }
      ]
    })
    this.calendrier = calendrier
    this.calendrierData = calendrierData
  }

  _onRender(context) {
    super._onRender(context)
    const el = this.element
    const setVal = (sel, val) => { const i = el.querySelector(sel); if (i) i.value = val }
    setVal("input[name='calendar.annee']", this.calendrierData.annee)
    setVal("select[name='calendar.mois']", this.calendrierData.mois.key)
    setVal("select[name='calendar.heure']", this.calendrierData.heure.key)
    RdDCalendrierEditor.setLimited(el.querySelector("input[name='calendar.jourDuMois']"), this.calendrierData.jourDuMois, 1, 28)
    RdDCalendrierEditor.setLimited(el.querySelector("input[name='calendar.minute']"), this.calendrierData.minute, 0, 119)
  }

  static setLimited(input, init, min, max) {
    if (!input) return
    input.value = init
    input.addEventListener("change", () => {
      const val = Number.parseInt(input.value)
      if (val < min) input.value = min
      if (val > max) input.value = max
    })
  }

  saveCalendrier() {
    const el = this.element
    const v = sel => el.querySelector(sel)?.value
    const annee = Number.parseInt(v("input[name='calendar.annee']"))
    const mois = v("select[name='calendar.mois']")
    const jour = Number.parseInt(v("input[name='calendar.jourDuMois']"))
    const heure = v("select[name='calendar.heure']")
    const minute = Number.parseInt(v("input[name='calendar.minute']"))
    this.calendrier.setNewTimestamp(RdDTimestamp.timestamp(annee, mois, jour, heure, minute))
  }

  updateData(calendrierData) {
    this.calendrierData = foundry.utils.deepClone(calendrierData)
  }
}
