import { TEMPLATE_DESCRIPTION, TEMPLATE_INVENTAIRE } from "../../common/_module.mjs";
import { ITEM_TYPES } from "../../constants.js";
import { RdDItemGemme } from "../../item/gemme.js";
import { RdDTimestamp } from "../../time/rdd-timestamp.js";
import RdDItemBaseSheet from "./common-item-sheet.mjs";

export default class RdDGemmeSheet extends RdDItemBaseSheet {
  static get ITEM_TYPE() { return ITEM_TYPES.gemme; }
  static get TEMPLATES() { return [TEMPLATE_DESCRIPTION, TEMPLATE_INVENTAIRE]; }

  static DEFAULT_OPTIONS = Object.assign({},
    RdDItemBaseSheet.DEFAULT_OPTIONS,
    {
      classes: ["fvtt-rdd", "item", "gemme"],
      position: { width: 448 },
      window: { contentClasses: ["gemme-content"] },
      actions: {
        enchanter: RdDGemmeSheet.#onEnchanter,
      },
    });

  static PARTS = {
    main: {
      template: "systems/foundryvtt-reve-de-dragon/templates/sheets/item/gemme.hbs",
    },
  };

  async _prepareContext() {
    const item = this.document
    const enchantement = RdDTimestamp.splitIndexDate(item.system.prdate)
    return Object.assign(
      await super._prepareContext(),
      {
        gemmeTypeList: RdDItemGemme.getGemmeTypeOptionList(),
        isEnchantementPossible: item.isEnchantementPossible,
        dateActuelle: game.system.rdd.calendrier.dateCourante(),
        enchantement,
      }
    );
  }

  _onChangeForm(event, formData) {
    const obj = formData?.object
    if (!obj) return super._onChangeForm(event, formData)

    if (event.target?.classList?.contains('date-enchantement')) {
      const jour = Number(this.element?.querySelector('input.date-enchantement[name="enchantement.jour"]')?.value)
      const moisEl = this.element?.querySelector('select.date-enchantement[name="enchantement.mois"]')
      if (moisEl) {
        const mois = RdDTimestamp.definition(moisEl.value)
        const indexDate = game.system.rdd.calendrier.getIndexFromDate(jour, mois.heure)
        obj['system.prdate'] = indexDate
        delete obj['enchantement.jour']
        delete obj['enchantement.mois']
      }
    }
    return super._onChangeForm(event, formData)
  }

  static async #onEnchanter(event, target) {
    const { DialogEnchanter } = await import("../../enchantement/dialog-enchanter.js")
    DialogEnchanter.enchanter(this.document)
  }
}
