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

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

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

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

  async _prepareContext() {
    const ctx = await super._prepareContext()
    const item = this.document

    ctx.isEnchantementPossible = item.isEnchantementPossible
    ctx.isSoins = item.system.categorie === 'Soin'
    ctx.isRepos = item.system.categorie === 'Repos'
    ctx.dateActuelle = game.system.rdd.calendrier.dateCourante()
    ctx.enchantement = RdDTimestamp.splitIndexDate(item.system.prdate)
    return ctx
  }

  async _onRender(context, options) {
    await super._onRender(context, options)

    this.element.querySelector('.item-potion-consommer')?.addEventListener('click', () => {
      const actor = this.document.parent
      if (actor) actor.consommerPotion(this.document)
    })

    this.element.querySelectorAll('.item-enchanter').forEach(el => {
      el.addEventListener('click', () => {
        if (!this.document.parent) {
          ui.notifications.warn("L'objet doit être possédé par un personnage pour être enchanté")
          return
        }
        DialogEnchanter.enchanter(this.document)
      })
    })

    this.element.querySelectorAll('.date-enchantement').forEach(el => {
      el.addEventListener('change', async () => {
        const jour = Number(this.element.querySelector('input.date-enchantement[name="enchantement.jour"]')?.value)
        const moisKey = this.element.querySelector('select.date-enchantement[name="enchantement.mois"]')?.value
        const mois = RdDTimestamp.definition(moisKey)
        if (mois) {
          const indexDate = game.system.rdd.calendrier.getIndexFromDate(jour, mois.heure)
          await this.document.update({ 'system.prdate': indexDate })
        }
      })
    })
  }
}
