import { ITEM_TYPES } from "../constants.js";
import { DialogEnchanter } from "../enchantement/dialog-enchanter.js";
import { RdDTimestamp } from "../time/rdd-timestamp.js";
import { RdDItemPotion } from "./potion.js";
import { RdDItemInventaireSheet } from "./sheet-base-inventaire.js";


export class RdDPotionItemSheet extends RdDItemInventaireSheet {

  static get ITEM_TYPE() { return ITEM_TYPES.potion };

  static $calculBonusHerbe(formData, herbesList, max) {
    if (Number(formData.system.herbebrins)) {
      let herbe = herbesList.find(h => h.name.toLowerCase() == formData.system.herbe.toLowerCase());
      if (herbe) {
        const brinsRequis = max - herbe.system.niveau;
        const brinsManquants = Math.max(brinsRequis - formData.system.herbebrins, 0);
        formData.system.herbebonus = Math.max(herbe.system.niveau - brinsManquants, 0);
      }
    }
  }

  async getData() {
    const formData = await super.getData()
    formData.isEnchantementPossible = this.item.isEnchantementPossible
    formData.isSoins = this.item.categorie == 'Soin'
    formData.isRepos = this.item.categorie == 'Repos'
    if (formData.isSoins) {
      const herbesSoins = await RdDItemPotion.herbesSoins()
      RdDPotionItemSheet.$calculBonusHerbe(formData, herbesSoins, 12);
      formData.herbesSoins = RdDItemPotion.buildHerbesList(herbesSoins, 12)
    }
    if (formData.isRepos) {
      const herbesRepos = await RdDItemPotion.herbesRepos()
      RdDPotionItemSheet.$calculBonusHerbe(formData, herbesRepos, 7);
      formData.herbesRepos = RdDItemPotion.buildHerbesList(herbesRepos, 7)
    }
    formData.dateActuelle = game.system.rdd.calendrier.dateCourante()
    formData.enchantement = RdDTimestamp.splitIndexDate(this.item.system.prdate)
    return formData
  }

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

    this.html.find('.item-enchanter').click((event) => DialogEnchanter.enchanter(this.item))

    this.html.find('.date-enchantement').change((event) => {
      const jour = Number(this.html.find('input.date-enchantement[name="enchantement.jour"]').val())
      const mois = RdDTimestamp.definition(this.html.find('select.date-enchantement[name="enchantement.mois"]').val())
      const indexDate = game.system.rdd.calendrier.getIndexFromDate(jour, mois.heure)
      this.item.update({ 'system.prdate': indexDate })
      console.warn(`Date d'enchantement modifiée ${jour}/${mois.heure}: ${indexDate}`)
    });

  }
}