import { renderTemplate } from "./constants.js"
import { Misc } from "./misc.js"
import { RdDUtility } from "./rdd-utility.js"

export class DialogFabriquerPotion extends foundry.applications.api.DialogV2 {
  static async create(actor, item) {
    const brinsMinimum = DialogFabriquerPotion.nombreBrinsMinimum(item)
    if (item.system.quantite < brinsMinimum) {
      ui.notifications.warn(`Vous avez ${item.system.quantite} brins de ${item.name}, il en faut au moins ${brinsMinimum} pour faire une potion!`)
      return
    }
    const potionData = DialogFabriquerPotion.prepareData(item, brinsMinimum)
    const content = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-fabriquer-potion-base.hbs", potionData)
    new DialogFabriquerPotion(actor, potionData, content).render({ force: true })
  }

  static prepareData(item, brinsMinimum) {
    const brinsOptimal = DialogFabriquerPotion.nombreBrinsOptimal(item)
    return foundry.utils.mergeObject(foundry.utils.deepClone(item), {
      nbBrinsSelect: RdDUtility.buildListOptions(brinsMinimum, brinsOptimal),
      nbBrins: Math.min(item.system.quantite, brinsOptimal),
      herbebonus: item.system.niveau
    })
  }

  constructor(actor, potionData, content) {
    super({
      title: `Fabriquer une potion de ${potionData.system.categorie}`,
      content,
      classes: ["dialogfabriquerpotion"],
      position: { width: 600, height: 160 },
      buttons: [
        { label: "Fabriquer", action: "fabriquer", callback: () => this.onFabriquer() }
      ]
    })
    this.actor = actor
    this.potionData = potionData
  }

  _onRender(context) {
    super._onRender(context)
    this.element.querySelector("[name='nbBrins']")?.addEventListener("change", event => {
      this.potionData.nbBrins = Misc.toInt(event.currentTarget.value)
      const optimal = DialogFabriquerPotion.nombreBrinsOptimal(this.potionData)
      const brinsManquants = Math.max(0, optimal - this.potionData.nbBrins)
      this.potionData.herbebonus = Math.max(0, this.potionData.system.niveau - brinsManquants)
    })
  }

  async onFabriquer() {
    const input = this.element.querySelector("[name='nbBrins']")
    if (input) input.dispatchEvent(new Event("change"))
    await this.actor.fabriquerPotion(this.potionData)
    this.close()
  }

  static nombreBrinsMinimum(herbeData) {
    switch (herbeData.system.categorie ?? '') {
      case "Soin": return 1 + Math.max(0, 12 - 2 * herbeData.system.niveau)
      case "Repos": return 1 + Math.max(0, 7 - 2 * herbeData.system.niveau)
    }
    return 1
  }

  static nombreBrinsOptimal(herbeData) {
    switch (herbeData.system.categorie ?? '') {
      case "Soin": return 12 - herbeData.system.niveau
      case "Repos": return 7 - herbeData.system.niveau
    }
    return 1
  }
}
