import { ITEM_TYPES } from "../constants.js";
import { Grammar } from "../grammar.js";
import { RdDItem } from "../item.js";
import { SystemCompendiums } from "../settings/system-compendiums.js";
import { ITEM_ACTIONS } from "./item-actions.js";
import { DialogEnchanter } from "./potion/dialog-enchanter.js";

const POTION_MAGIQUE = ['AlchimieEnchante', 'ReposEnchante', 'SoinEnchante', 'AutreEnchante']
const POTION_ENCHANTABLE = ['Alchimie', 'Repos', 'Soin', 'Autre']
  .concat(POTION_MAGIQUE)

const MAP_CATEGORIE_ENCHANTEMENT = [
  { basique: 'Alchimie', enchante: 'AlchimieEnchante' },
  { basique: 'Repos', enchante: 'ReposEnchante' },
  { basique: 'Soin', enchante: 'SoinEnchante' },
  { basique: 'Autre', enchante: 'AutreEnchante' }]

export class RdDItemPotion extends RdDItem {

  static async herbesSoins() {
    return await RdDItemPotion.$listHerbes(it => Grammar.equalsInsensitive(it.system.categorie, 'Soin') && it.system.niveau > 0)
  }
  static async herbesRepos() {
    return await RdDItemPotion.$listHerbes(it => Grammar.equalsInsensitive(it.system.categorie, 'Repos') && it.system.niveau > 0)
  }

  static async $listHerbes(filter) {
    const herbes = await SystemCompendiums.getWorldOrCompendiumItems('herbe', 'faune-flore-mineraux');
    return herbes.filter(filter)
  }

  static get defaultIcon() {
    return "systems/foundryvtt-reve-de-dragon/icons/objets/liqueur_de_bagdol.webp"
  }

  prepareDerivedData() {
    super.prepareDerivedData()
    this.system.puissance = this.system.magique ? this.calculPuissance() : 0
  }

  isPotion() { return true }
  isEnchantable() { return POTION_ENCHANTABLE.includes(this.system.categorie) }
  isMagique() { return POTION_MAGIQUE.includes(this.system.categorie) }

  itemSpecificActions() {
    return ITEM_ACTIONS[ITEM_TYPES.potion]
  }

  getActions(options = { warnIfNot: true }) {
    const actionConsommer = this.prepareAction('Consommer', options.warnIfNot);
    if (this.isEnchantable()) {
      return [
        actionConsommer,
        this.prepareAction('Enchanter', options.warnIfNot)
      ]
    }
    return [
      actionConsommer
    ]
  }
  // TDOD: purifier?
  getUtilisation() {
    switch (this.system.categorie) {
      case 'Alchimie': case 'AlchimieEnchante':
      case 'AlchimieAutre':
        return 'alchimie'
      case 'Cuisine': return 'cuisine'
      case 'Remede': case 'Repos': case 'ReposEnchante': case 'Soin': case 'SoinEnchante':
        return 'soins'
    }
    return ''
  }

  _potionChatData() {
    return [
      `<b>Rareté</b>: ${this.system.rarete}`,
      `<b>Catégorie</b>: ${this.system.categorie}`,
      ...this._inventaireTemplateChatData()
    ]
  }

  async enchanterPotion() {
    const actor = this.parent;
    if (actor && (!actor.isPersonnage() || !actor.isHautRevant())) {
      ui.notifications.info('Seul un haut rêvant peut enchanter une potion')
      return
    }
    const dailog = await DialogEnchanter.create(this, actor, (updates) => this.$onEnchanterPotion(updates));
    dailog.render(true)
  }

  perteRevePotion() {
    if (this.system.magique && !this.system.prpermanent && this.system.pr > 0) {
      const nouveauReve = Math.max(this.system.pr - 1, 0)
      return {
        _id: this.id,
        name: this.name,
        img: this.img,
        'system.pr': nouveauReve,
        'system.quantite': nouveauReve > 0 ? this.system.quantite : 0,
        'system.magique': nouveauReve > 0
      }
    }
    return undefined
  }

  async $onEnchanterPotion(enchanter) {
    if (enchanter.nouveaupr == 0) {
      await this.update({
        'system.pr': 0,
        'system.purifie': false,
        'system.magique': false,
        'system.categorie': this.categorieEnchantement().basique,
        'system.prpermanent': false,
        'system.prdate': 0,
        'system.quantite': this.parent ? 0 : this.system.quantite
      })
    }
    else {
      await this.update({
        'system.pr': enchanter.nouveaupr,
        'system.purifie': enchanter.purifier,
        'system.magique': true,
        'system.categorie': this.categorieEnchantement().enchante,
        'system.prpermanent': enchanter.prpermanent,
        'system.prdate': RdDItemPotion.dateEnchantement()
      })
    }
    this.sheet?.render(true)
  }

  calculPuissance() { return this.system.herbebonus * this.system.pr }

  categorieEnchantement() {
    const categorie = this.system.categorie
    const categorieEnchantement = MAP_CATEGORIE_ENCHANTEMENT.find(it => [it.basique, it.enchante].includes(categorie))
    return categorieEnchantement ?? { basique: categorie, enchante: categorie }
  }

  static dateEnchantement() {
    return game.system.rdd.calendrier.getTimestamp().debutJournee().indexDate
  }

  static buildHerbesList(listeHerbes, max) {
    let list = {}
    for (let herbe of listeHerbes) {
      let brins = max - herbe.system.niveau;
      list[herbe.name] = `${herbe.name} (Bonus: ${herbe.system.niveau}, Brins: ${brins})`;
    }
    list['Autre'] = 'Autre (Bonus: variable, Brins: variable)'
    return list;
  }

}