import { ITEM_TYPES } from "../constants.js"
import { APPRECIATION } from "../moral/apprecier.mjs"
import { RollBasicParts } from "./roll-basic-parts.mjs"
import { DIFF, ROLL_TYPE_CUISINE, RollConstants } from "./roll-constants.mjs"
import { PART_CUISINE } from "./roll-part-cuisine.mjs"
import { RollType } from "./roll-type.mjs"

export class RollTypeCuisine extends RollType {
  get code() { return ROLL_TYPE_CUISINE }
  get name() { return `Cuisiner un plat` }

  visible(rollData) {
    return rollData.active.actor.isPersonnage()
      && RollConstants.findCompetence(rollData, 'Cuisine')
  }

  title(rollData) {
    const current = rollData.current[PART_CUISINE]
    return current.recette ? `prépare une recette: ${current.label}` : `prépare: ${current.label}`
  }

  onSelect(rollData) {
    this.setDiffType(rollData, DIFF.AUCUN)
  }

  getResult(rollData, impacts) {
    const current = rollData.current[PART_CUISINE]
    const qualite = rollData.rolled.ptQualite + current.qualite

    const result = {
      qualite: qualite,
      exotisme: Math.min(Math.min(qualite, current.exotisme ?? 0), 0),
      messages: []
    }
    if (current.fabriquer) {
      const plat = this.$prepareNourriture(rollData.active.name, current, result)
      result.messages.push(`${plat.system.quantite} ${plat.name} ont été préparés dans l'équipement`)
      impacts.addCreated('Item', plat)
      result.plat = { id: plat.id }
    }
    if (current.ingredient) {
      const quantite = Math.min(current.proportions, current.ingredient.system.quantite)
      if (quantite == current.ingredient.system.quantite) {
        impacts.addDeleted('Item', current.ingredient)
        result.messages.push(`Il n'y a plus de ${ingredient.name}`)
      }
      else {
        impacts.addDelta('Item', current.ingredient, 'system.quantite', -current.proportions)
        result.messages.push(`${current.proportions} ${current.ingredient.name} ont été utilisés`)
      }
    }
    return result
  }

  onApplyImpacts(roll, impacts) {
    if (roll.result.plat) {
      // le plat n'est pas créé immédiatement, il faut donc retrouver l'id
      roll.result.plat.id = impacts.findCreatedId('Item', roll.result.plat.id)
    }
  }

  $prepareNourriture(cuisinier, current, result) {
    return {
      id: foundry.utils.randomID(16),
      name: current.label,
      img: current.img,
      type: ITEM_TYPES.nourritureboisson,
      system: {
        sust: current.sust,
        cuisinier: cuisinier,
        exotisme: result.exotisme,
        encombrement: 0.1,
        quantite: current.proportions,
        qualite: result.qualite,
        cout: result.qualite > 0 ? (result.qualite * 0.01) : 0.01,
        appreciation: APPRECIATION.CUISINE
      }
    }
  }

  async onFaireGouter(savedRoll) {
    const actor = RollBasicParts.getTokenActor(savedRoll).actor
    const platId = savedRoll.result.plat.id
    const plat = actor.items.get(platId)
    await plat?.proposerVente()
  }

}

