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

/**
 * Extend the base Dialog entity by defining a custom window to perform roll.
 * @extends {Dialog}
 */
export class RdDCalendrierEditor extends Dialog {

  /* -------------------------------------------- */
  constructor(html, calendrier, calendrierData) {
    let dialogConf = {
      content: html,
      title: "Editeur de date/heure",
      buttons: {
        save: { label: "Enregistrer", callback: html => this.saveCalendrier() }
      },
      default: "save"
    };
    let dialogOptions = { classes: ["rdd-dialog-calendar-editor"], width: 400, height: 'fit-content', 'z-index': 99999 }
    super(dialogConf, dialogOptions)

    this.calendrier = calendrier;
    this.calendrierData = calendrierData;
  }

  activateListeners(html) {
    super.activateListeners(html);
    this.html = html;

    this.html.find("input[name='calendar.annee']").val(this.calendrierData.annee);
    this.html.find("select[name='calendar.mois']").val(this.calendrierData.mois.key);
    this.html.find("select[name='calendar.heure']").val(this.calendrierData.heure.key);
    RdDCalendrierEditor.setLimited(this.html.find("input[name='calendar.jourDuMois']"), this.calendrierData.jourDuMois, 1, 28);
    RdDCalendrierEditor.setLimited(this.html.find("input[name='calendar.minute']"), this.calendrierData.minute, 0, 119);
  }

  static setLimited(input, init, min, max) {
    input.val(init);
    input.change(event => {
      const val = Number.parseInt(input.val());
      if (val < min) {
        input.val(min);
      }
      if (val > max) {
        input.val(max);
      }
    });

  }

  /* -------------------------------------------- */
  saveCalendrier() {
    const annee = Number.parseInt(this.html.find("input[name='calendar.annee']").val());
    const mois = this.html.find("select[name='calendar.mois']").val();
    const jour = Number.parseInt(this.html.find("input[name='calendar.jourDuMois']").val());
    const heure = this.html.find("select[name='calendar.heure']").val();
    const minute = Number.parseInt(this.html.find("input[name='calendar.minute']").val());

    this.calendrier.setNewTimestamp(RdDTimestamp.timestamp(annee, mois, jour, heure, minute))
  }

  /* -------------------------------------------- */
  updateData(calendrierData) {
    this.calendrierData = foundry.utils.duplicate(calendrierData);
  }

}