/* -------------------------------------------- */
import { HeritiersUtility } from "./heritiers-utility.js";
import { HeritiersRollDialog } from "./applications/heritiers-roll-dialog.mjs";

/* -------------------------------------------- */
const __degatsBonus = [-2, -2, -1, -1, 0, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 8, 8, 9, 9, 10, 10]
const __vitesseBonus = [-2, -2, -1, -1, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]

/* -------------------------------------------- */
/**
 * Extend the base Actor entity by defining a custom roll data structure which is ideal for the Simple system.
 * @extends {Actor}
 */
export class HeritiersActor extends Actor {

  /* -------------------------------------------- */
  /**
   * Override the create() function to provide additional SoS functionality.
   *
   * This overrided create() function adds initial items
   * Namely: Basic skills, money,
   *
   * @param {Object} data        Barebones actor data which this function adds onto.
   * @param {Object} options     (Unused) Additional options which customize the creation workflow.
   *
   */

  static async create(data, options) {

    // Case of compendium global import
    if (data instanceof Array) {
      return super.create(data, options);
    }
    // If the created actor has items (only applicable to duplicated actors) bypass the new actor creation logic
    if (data.items) {
      let actor = super.create(data, options);
      return actor;
    }

    if (data.type == 'personnage') {
      const skills = await HeritiersUtility.loadCompendium("fvtt-les-heritiers.competences")
      data.items = []
      for (let skill of skills) {
        if (skill.system.categorie == "utile" && skill.system.profil != "magie") {
          data.items.push(skill.toObject())
        }
      }
    }
    if (data.type == 'pnj') {
    }

    return super.create(data, options);
  }

  /* -------------------------------------------- */
  prepareArme(arme) {
    arme = foundry.utils.duplicate(arme)
    arme.system.isMelee = HeritiersUtility.isArmeMelee(arme)
    return arme
  }

  /* -------------------------------------------- */
  getWeapons() {
    let armes = []
    for (let arme of this.items) {
      if (arme.type == "arme") {
        armes.push(this.prepareArme(arme))
      }
    }
    return armes
  }
  /* -------------------------------------------- */
  getOtherMeleeWeapons(excludeArme) {
    let armes = []
    for (let arme of this.items) {
      if (HeritiersUtility.isArmeMelee(arme) && arme.id != excludeArme._id) {
        armes.push(this.prepareArme(arme))
      }
    }
    return armes
  }
  /* -------------------------------------------- */
  getMonnaies() {
    return this.items.filter(it => it.type == "monnaie")
  }

  /* -----------------------  --------------------- */
  addMember(actorId) {
    let members = foundry.utils.duplicate(this.system.members)
    members.push({ id: actorId })
    this.update({ 'system.members': members })
  }
  async removeMember(actorId) {
    let members = this.system.members.filter(it => it.id != actorId)
    this.update({ 'system.members': members })
  }

  /* -----------------------  --------------------- */
  getItemSorted(types) {
    let items = this.items.filter(item => types.includes(item.type)) || []
    HeritiersUtility.sortArrayObjectsByName(items)
    return items
  }
  getEquipments() {
    return this.getItemSorted(["equipement", "accessoire"])
  }
  getAvantages() {
    return this.getItemSorted(["avantage"])
  }
  getDesavantages() {
    return this.getItemSorted(["desavantage"])
  }
  getMonnaies() {
    return this.getItemSorted(["monnaie"])
  }
  getArmors() {
    return this.getItemSorted(["protection"])
  }
  getTalents() {
    return this.getItemSorted(["talent"])
  }
  getContacts() {
    return this.getItemSorted(["contact"])
  }
  getAtouts() {
    return this.getItemSorted(["atoutfeerique"])
  }
  getCapacites() {
    return this.getItemSorted(["capacitenaturelle"])
  }
  getFee() {
    return this.items.find(item => item.type == "fee")
  }
  getProfils() {
    return this.getItemSorted(["profil"])
  }
  getPouvoirs() {
    let pouvoirs = []
    for (let item of this.items) {
      if (item.type == "pouvoir") {
        let itemObj = foundry.utils.duplicate(item)
        itemObj.maxUsage = this.getPouvoirUsageMax(item)
        pouvoirs.push(itemObj)
      }
    }
    HeritiersUtility.sortArrayObjectsByName(pouvoirs)
    return pouvoirs
  }
  getSorts() {
    return this.getItemSorted(["sort"])
  }
  getCompetencesMagie() {
    let comp = []
    for (let item of this.items) {
      if (item.type == "competence" && item.system.profil == "magie") {
        let itemObj = foundry.utils.duplicate(item)
        comp.push(itemObj)
      }
    }
    HeritiersUtility.sortArrayObjectsByName(comp)
    return comp
  }

  prepareMagie() {
    let magieList = []
    for (let item of this.items) {
      if (item.type == "competence" && item.system.profil == "magie") {
        let magie = {}
        magie.name = item.name
        magie.competence = foundry.utils.duplicate(item)
        magie.rang = Math.round(item.system.niveau / 2);
        magie.rangGenericName = game.system.lesheritiers.config.rangName[magie.rang];
        console.log("Magie", item.name, item.system.niveau, magie.rang, magie.rangGenericName)
        //magie.rangSpecificName = game.system.lesheritiers.config.rangNameSpecific[item.name][magie.rangGenericName];
        magie.sorts = {}
        if (item.name == "Magie du Clan") {
          magie.sorts = {
            "soufflecombat": {
              1: { nomNiveau: magie.competence.system.nomniveausouffle.soufflecombat["1"], sorts: [] },
              2: { nomNiveau: magie.competence.system.nomniveausouffle.soufflecombat["2"], sorts: [] },
              3: { nomNiveau: magie.competence.system.nomniveausouffle.soufflecombat["3"], sorts: [] },
              4: { nomNiveau: magie.competence.system.nomniveausouffle.soufflecombat["4"], sorts: [] }
            },
            "soufflemouvement": {
              1: { nomNiveau: magie.competence.system.nomniveausouffle.soufflemouvement["1"], sorts: [] },
              2: { nomNiveau: magie.competence.system.nomniveausouffle.soufflemouvement["2"], sorts: [] },
              3: { nomNiveau: magie.competence.system.nomniveausouffle.soufflemouvement["3"], sorts: [] },
              4: { nomNiveau: magie.competence.system.nomniveausouffle.soufflemouvement["4"], sorts: [] }
            },
            "souffleesprit": {
              1: { nomNiveau: magie.competence.system.nomniveausouffle.souffleesprit["1"], sorts: [] },
              2: { nomNiveau: magie.competence.system.nomniveausouffle.souffleesprit["2"], sorts: [] },
              3: { nomNiveau: magie.competence.system.nomniveausouffle.souffleesprit["3"], sorts: [] },
              4: { nomNiveau: magie.competence.system.nomniveausouffle.souffleesprit["4"], sorts: [] }
            }
          }
          for (let sort of this.items) {
            if (sort.type == "sort" && sort.system.competence == item.name) {
              let sortObj = foundry.utils.duplicate(sort)
              sortObj.sdValue = HeritiersUtility.getSDSortValue(Number(sort.system.niveau))
              if (!magie.sorts[sort.system?.souffle]) {
                console.warn("Sort with unknown souffle ", sort.system.souffle, sort)
                continue
              }
              magie.sorts[sort.system.souffle][Number(sort.system.niveau)].sorts.push(sortObj)
            }
          }
        } else {
          magie.sorts = {
            1: { nomNiveau: magie.competence.system.nomniveau["1"], sorts: [] },
            2: { nomNiveau: magie.competence.system.nomniveau["2"], sorts: [] },
            3: { nomNiveau: magie.competence.system.nomniveau["3"], sorts: [] },
            4: { nomNiveau: magie.competence.system.nomniveau["4"], sorts: [] }
          }
          for (let sort of this.items) {
            if (sort.type == "sort" && sort.system.competence == item.name) {
              let sortObj = foundry.utils.duplicate(sort)
              sortObj.sdValue = HeritiersUtility.getSDSortValue(Number(sort.system.niveau))
              magie.sorts[Number(sort.system.niveau)].sorts.push(sortObj)
            }
          }
        }
        magieList.push(magie)
      }
    }
    return magieList
  }

  /* -------------------------------------------- */
  getSkills() {
    let comp = []
    for (let item of this.items) {
      item = foundry.utils.duplicate(item)
      if (item.type == "competence") {
        comp.push(item)
      }
    }
    return HeritiersUtility.sortByName(comp)
  }

  /* -------------------------------------------- */
  prepareUtileSkill(item) {
    let specList = []
    if (item?.system?.categorie == "utile") {
      for (let spec of item.system.specialites) {
        specList.push(spec.name)
      }
    }
    item.nbSpec = specList.length
    item.specList = specList.toString()
  }

  /* -------------------------------------------- */
  organizeMagicSkills() {
    let comp = {}
    for (let key in game.system.lesheritiers.config.competenceProfil) {
      if (game.system.lesheritiers.config.competenceProfil[key].kind == "magical")
        comp[key] = { skills: [], niveau: 0 }
    }
    for (let item of this.items) {
      if (item.type == "competence") {
        if (item.system.categorie == "utile" && comp[item.system.profil]) {
          this.prepareUtileSkill(item)
          comp[item.system.profil].skills.push(item)
        }
      }
    }

    for (let key in comp) {
      HeritiersUtility.sortArrayObjectsByName(comp[key].skills)
    }
    return Object.fromEntries(Object.entries(comp).sort())
  }

  /* -------------------------------------------- */
  organizeUtileSkills(kind = "mental") {
    let comp = {}
    for (let key in game.system.lesheritiers.config.competenceProfil) {
      if (game.system.lesheritiers.config.competenceProfil[key].kind == kind)
        comp[key] = { skills: [], niveau: this.system.competences[key].niveau, rang: this.system.competences[key].rang }
    }
    for (let item of this.items) {
      if (item.type == "competence") {
        if (item.system.categorie == "utile" && comp[item.system.profil]) {
          this.prepareUtileSkill(item)
          comp[item.system.profil].skills.push(item)
        }
      }
    }

    for (let key in comp) {
      HeritiersUtility.sortArrayObjectsByName(comp[key].skills)
    }
    return Object.fromEntries(Object.entries(comp).sort())
  }

  /* -------------------------------------------- */
  organizeContacts() {
    let contactList = {}
    for (let item of this.items) {
      if (item.type == "contact") {
        let c = contactList[item.system.contacttype] || { label: game.system.lesheritiers.config.contactType[item.system.contacttype], list: [] }
        c.list.push(item)
        contactList[item.system.contacttype] = c
      }
    }
    for (let key in contactList) {
      HeritiersUtility.sortArrayObjectsByName(contactList[key].list)
    }
    return contactList
  }

  /* -------------------------------------------- */
  organizeFutileSkills() {
    let comp = []
    for (let item of this.items) {
      if (item.type == "competence") {
        if (item.system.categorie == "futile") {
          comp.push(item)
        }
      }
    }
    HeritiersUtility.sortArrayObjectsByName(comp)
    return HeritiersUtility.sortByName(comp)
  }

  /* -------------------------------------------- */
  getDefenseBase() {
    return Math.max(this.system.attributs.tre.value, this.system.attributs.pui.value)
  }

  /* -------------------------------------------- */
  getVitesseBase() {
    return 5 + __vitesseBonus[this.system.attributs.adr.value]
  }
  /* -------------------------------------------- */
  getProtection() {
    let equipProtection = 0
    for (let armor in this.items) {
      if (armor.type == "protection" && armor.system.equipped) {
        equipProtection += Number(armor.system.protection)
      }
    }
    if (equipProtection < 4) {
      return 4 + equipProtection // Cas des boucliers + sans armure
    }
    return equipProtection // Uniquement la protection des armures + boucliers
  }

  /* -------------------------------------------- */
  getCombatValues() {
    let combat = {
    }
    return combat
  }

  /* -------------------------------------------- */
  async prepareData() {
    super.prepareData();
  }

  /* -------------------------------------------- */
  getMaxRangMagie() {
    let niv = 0
    let bestMagie
    for (let comp of this.items) {
      if (comp.type == "competence" && comp.system.profil == "magie") {
        if (comp.system.niveau > niv) {
          bestMagie = comp
          niv = comp.system.niveau
        }
      }
    }
    if (bestMagie) {
      return Math.round(bestMagie.system.niveau / 2)
    }
    return 0
  }

  /* -------------------------------------------- */
  prepareDerivedData() {
    // Calculate derived PV max
    let pvMax = (this.system.caracteristiques.con.rang * 3) + 9 + this.system.pv.mod
    this.system.pv.max = pvMax

    // Calculate derived Points d'Âme max
    if (this.system.biodata.magie || this.type == "pnj") {
      let pointsAmes = this.system.caracteristiques.esp.rang + this.system.caracteristiques.san.rang + this.getMaxRangMagie()
      this.system.magie.pointsame.max = pointsAmes
    }

    if (this.type == 'personnage') {
      // Calculate rang for each competence profile
      let competencesRangs = {
        aventurier: 0,
        combattant: 0,
        erudit: 0,
        gentleman: 0,
        roublard: 0,
        savant: 0
      }

      // Sum up niveau for each profil
      for (let item of this.items) {
        if (item.type == "competence" && item.system.profil && item.system.categorie == "utile") {
          let profil = item.system.profil.toLowerCase()
          if (competencesRangs.hasOwnProperty(profil)) {
            competencesRangs[profil] += item.system.niveau
          }
        }
      }

      // Calculate rang (total / 4, rounded down) for each competence
      for (let profil in competencesRangs) {
        let total = competencesRangs[profil]
        let rang = Math.floor(total / 4)
        if (this.system.competences[profil]) {
          this.system.competences[profil].rang = rang
        }
      }
    }

    super.prepareDerivedData()
  }

  /* -------------------------------------------- */
  _preUpdate(changed, options, user) {

    super._preUpdate(changed, options, user);
  }

  /* -------------------------------------------- */
  getItemById(id) {
    let item = this.items.find(item => item.id == id);
    if (item) {
      item = foundry.utils.duplicate(item)
    }
    return item;
  }

  /* -------------------------------------------- */
  async equipItem(itemId) {
    let item = this.items.find(item => item.id == itemId)
    if (item?.system) {
      let update = { _id: item.id, "system.equipped": !item.system.equipped }
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  editItemField(itemId, itemType, itemField, dataType, value) {
    let item = this.items.find(item => item.id == itemId)
    if (item) {
      console.log("Item ", item, itemField, dataType, value)
      if (dataType) {
        if (dataType.toLowerCase() == "number") {
          value = Number(value)
        } else if (dataType.toLowerCase() == "boolean") {
          value = Boolean(value)
        } else {
          value = String(value)
        }
      }
      let update = { _id: item.id, [`system.${itemField}`]: value };
      this.updateEmbeddedDocuments("Item", [update])
    }
  }

  /* -------------------------------------------- */
  getPvMalus() {
    if (this.system.pv.value > 0) {
      if (this.system.pv.value < 5) {
        return { name: "Santé", value: -2 }
      }
      if (this.system.pv.value < this.system.pv.max / 2) {
        return { name: "Santé", value: -1 }
      }
      return { name: "Santé", value: 0 }
    }
    return { name: "Moribond(e)", value: -50 }
  }

  /* -------------------------------------------- */
  compareName(a, b) {
    if (a.name < b.name) {
      return -1;
    }
    if (a.name > b.name) {
      return 1;
    }
    return 0;
  }

  /* -------------------------------------------- */
  getCarac(attrKey) {
    return foundry.utils.duplicate(this.system.caracteristiques)
  }

  /* -------------------------------------------- */
  getBonusDegats() {
    return 0;
  }

  /* -------------------------------------------- */
  async equipGear(equipmentId) {
    let item = this.items.find(item => item.id == equipmentId);
    if (item?.system) {
      let update = { _id: item.id, "system.equipped": !item.system.equipped };
      await this.updateEmbeddedDocuments('Item', [update]); // Updates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  getSubActors() {
    let subActors = [];
    for (let id of this.system.subactors) {
      subActors.push(foundry.utils.duplicate(game.actors.get(id)));
    }
    return subActors;
  }
  /* -------------------------------------------- */
  async addSubActor(subActorId) {
    let subActors = foundry.utils.duplicate(this.system.subactors);
    subActors.push(subActorId);
    await this.update({ 'system.subactors': subActors });
  }
  /* -------------------------------------------- */
  async delSubActor(subActorId) {
    let newArray = [];
    for (let id of this.system.subactors) {
      if (id != subActorId) {
        newArray.push(id);
      }
    }
    await this.update({ 'system.subactors': newArray });
  }

  /* -------------------------------------------- */
  getTotalAdversite() {
    return this.system.adversite.bleue + this.system.adversite.rouge + this.system.adversite.noire
  }

  /* -------------------------------------------- */
  async incDecAdversite(adv, incDec = 0) {
    let adversite = foundry.utils.duplicate(this.system.adversite)
    adversite[adv] += Number(incDec)
    adversite[adv] = Math.max(adversite[adv], 0)
    this.update({ 'system.adversite': adversite })
  }

  /* -------------------------------------------- */
  async incDecQuantity(objetId, incDec = 0) {
    let objetQ = this.items.get(objetId)
    if (objetQ) {
      let newQ = objetQ.system.quantite + incDec
      newQ = Math.max(newQ, 0)
      const updated = await this.updateEmbeddedDocuments('Item', [{ _id: objetQ.id, 'system.quantite': newQ }]); // pdates one EmbeddedEntity
    }
  }

  /* -------------------------------------------- */
  computeRichesse() {
    let valueSC = 0
    for (let monnaie of this.items) {
      if (monnaie.type == "monnaie") {
        valueSC += Number(monnaie.system.prixsc) * Number(monnaie.system.quantite)
      }
    }
    return HeritiersUtility.computeMonnaieDetails(valueSC)
  }

  /* -------------------------------------------- */
  computeValeurEquipement() {
    let valueSC = 0
    for (let equip of this.items) {
      if (equip.type == "equipement" || equip.type == "arme" || equip.type == "protection") {
        valueSC += Number(equip.system.prixsc) * Number(equip.system.quantite ?? 1)
        valueSC += (Number(equip.system.prixca) * Number(equip.system.quantite ?? 1)) * 20
        valueSC += (Number(equip.system.prixpo) * Number(equip.system.quantite ?? 1)) * 400
      }
    }
    return HeritiersUtility.computeMonnaieDetails(valueSC)
  }

  /* -------------------------------------------- */
  getCompetence(compId) {
    return this.items.get(compId)
  }

  /* -------------------------------------------- */
  async setPredilectionUsed(compId, predIdx) {
    let comp = this.items.get(compId)
    let pred = foundry.utils.duplicate(comp.system.predilections)
    pred[predIdx].used = true
    await this.updateEmbeddedDocuments('Item', [{ _id: compId, 'system.predilections': pred }])
  }

  /* -------------------------------------------- */
  getInitiativeScore() {
    let init = this.getFlag("world", "last-initiative")
    return init || -1
  }

  /* -------------------------------------------- */
  getBestDefenseValue() {
    let defenseList = this.items.filter(item => (item.type == "arme") && item.system.equipped)
    let maxDef = 0
    let bestArme
    for (let arme of defenseList) {
      if (arme.type == "arme") {
        arme = this.prepareArme(arme)
      }
      if (arme.system.totalDefensif > maxDef) {
        maxDef = arme.system.totalDefensif
        bestArme = foundry.utils.duplicate(arme)
      }
    }
    return bestArme
  }

  /* -------------------------------------------- */
  searchRelevantTalents(competence) {
    let talents = []

    for (let talent of this.items) {
      if (talent.type == "talent" && talent.system.isautomated && talent.system.automations.length > 0) {
        for (let auto of talent.system.automations) {
          if (auto.eventtype === "prepare-roll") {
            if (auto.competence.toLowerCase() == competence.name.toLowerCase()) {
              talent = foundry.utils.duplicate(talent)
              talent.system.bonus = auto.bonus
              talent.system.baCost = auto.baCost
              talents.push(talent)
            }
          }
        }
      }
    }
    return talents
  }
  /* -------------------------------------------- */
  getCurrentParade() {
    if (this.system.statutmasque == "masque") {
      return this.system.combat.parade.masquee
    }
    return this.system.combat.parade.demasquee
  }
  /* -------------------------------------------- */
  getCurrentEsquive() {
    if (this.system.statutmasque == "masque") {
      return this.system.combat.esquive.masquee
    }
    return this.system.combat.esquive.demasquee
  }
  getCurrentResistancePhysique() {
    return this.system.combat.resistancephysique.value
  }
  /* -------------------------------------------- */
  getTricherie() {
    return this.system.rang.tricherie.value
  }
  /* -------------------------------------------- */
  getHeritages() {
    return this.system.rang.heritage.value
  }
  /* -------------------------------------------- */
  incDecTricherie(value) {
    let tricherie = this.system.rang.tricherie
    tricherie.value += value
    if (tricherie.value < 0 || tricherie.value > tricherie.max) {
      ui.notifications.warn("Pas assez de points de Tricherie !")
      return false
    }
    tricherie.value = Math.max(tricherie.value, 0)
    tricherie.value = Math.min(tricherie.value, tricherie.max)
    this.update({ 'system.rang.tricherie': tricherie })
    return true
  }
  /* -------------------------------------------- */
  /* -------------------------------------------- */
  // Returns the combattant root competence formatted for rollData, used for PNJ attacks
  _getCombattantCompetence() {
    const combattant = this.system.competences.combattant
    return { name: combattant.label, system: { niveau: combattant.niveau } }
  }

  /* -------------------------------------------- */
  getPireCompetence(compName1, compName2) {
    let comp1 = this.items.find(it => it.name == compName1)
    let comp2 = this.items.find(it => it.name == compName2)
    if (comp1 && comp2) {
      if (comp1.system.niveau > comp2.system.niveau) {
        return comp1
      } else {
        return comp2
      }
    }
    return undefined
  }

  /* -------------------------------------------- */
  getCommonRollData(compId = undefined, compName = undefined) {
    let rollData = HeritiersUtility.getBasicRollData()
    rollData.alias = this.name
    rollData.actorImg = this.img
    rollData.actorId = this.id
    rollData.tokenId = this.token?.id
    rollData.img = this.img
    rollData.caracList = this.getCarac()
    rollData.caracKey = "agi"
    rollData.tricherie = this.getTricherie()
    rollData.heritage = this.getHeritages()
    rollData.useTricherie = false
    rollData.useSpecialite = false
    rollData.useHeritage = false
    rollData.pouvoirPointsUsage = 1
    rollData.rulesMalus.push(this.getPvMalus())

    if (compId) {
      rollData.competence = foundry.utils.duplicate(this.items.get(compId) || {})
      this.prepareUtileSkill(rollData.competence)
      rollData.actionImg = rollData.competence?.img
    }
    if (compName) {
      rollData.competence = foundry.utils.duplicate(this.items.find(item => item.name.toLowerCase() == compName.toLowerCase()) || {})
      if (rollData.competence?.name) {
        this.prepareUtileSkill(rollData.competence)
        rollData.actionImg = rollData.competence?.img
      } else {
        rollData.competence = undefined
      }
    }
    HeritiersUtility.updateWithTarget(rollData)

    return rollData
  }
  /* -------------------------------------------- */
  async rollInitiative() {
    let rollData = this.getCommonRollData(undefined, "Art de la guerre")
    rollData.mode = "init"
    if (this.system.caracteristiques["san"].value > this.system.caracteristiques["per"].value) {
      rollData.caracKey = "san"
    } else {
      rollData.caracKey = "per"
    }
    rollData.carac = this.system.caracteristiques[rollData.caracKey]
    await HeritiersRollDialog.create(this, rollData)
  }

  /* -------------------------------------------- */
  async rollCarac(key, isInit = false) {
    let rollData = this.getCommonRollData()
    rollData.mode = "carac"
    rollData.carac = this.system.caracteristiques[key]
    rollData.caracKey = key
    await HeritiersRollDialog.create(this, rollData)
  }

  /* -------------------------------------------- */
  async rollRang(key, isInit = false) {
    let rollData = this.getCommonRollData()
    rollData.mode = "rang"
    rollData.rang = this.system.rang[key]
    rollData.rangKey = key
    await HeritiersRollDialog.create(this, rollData)
  }
  /* -------------------------------------------- */
  async rollRootCompetence(compKey) {
    let rollData = this.getCommonRollData()
    rollData.mode = "competence"
    rollData.competence = { name: this.system.competences[compKey].label, system: { niveau: this.system.competences[compKey].niveau } }
    console.log("RollDatra", rollData)
    await HeritiersRollDialog.create(this, rollData)
  }

  /* -------------------------------------------- */
  async rollCompetence(compId) {
    let rollData = this.getCommonRollData(compId)
    rollData.mode = "competence"
    console.log("RollDatra", rollData)
    await HeritiersRollDialog.create(this, rollData)
  }

  /* -------------------------------------------- */
  inDecCarac(key, incDec) {
    let carac = this.system.caracteristiques[key]
    carac.value += incDec
    if (carac.value < 0 || carac.value > carac.rang) {
      ui.notifications.warn("Pas assez de points dans cette caractéristique ou rang max atteint !")
      return false
    }
    carac.value = Math.max(carac.value, 0)
    carac.value = Math.min(carac.value, carac.rang)
    this.update({ [`system.caracteristiques.${key}`]: carac })
    return true
  }

  /* -------------------------------------------- */
  async rollSort(sortId) {
    let sort = this.items.get(sortId)
    let comp = this.items.find(it => it.type == "competence" && it.name.toLowerCase() == sort.system.competence.toLowerCase())
    if (!comp) {
      ui.notifications.warn("Compétence de magie associée non trouvée !")
      return
    }
    if (sort.system.informatif) {
      if (sort.system.texteinformatif) {
        let chatData = { user: game.user.id, speaker: { actor: this, alias: this.name }, content: `<div class="heritiers-informatif-sort"><h4>Sort informatif !</h4>${sort.system.texteinformatif}</div>` }
        ChatMessage.create(chatData)
      } else {
        ui.notifications.info("Ce sort est uniquement informatif et ne peut pas être lancé.")
      }
      return
    }

    let rollData = this.getCommonRollData(comp.id)
    rollData.mode = "sort"
    rollData.sort = foundry.utils.duplicate(sort)
    rollData.sdValue = HeritiersUtility.getSDSortValue(Number(sort.system.niveau))
    if (Number(sort.system.sdspecial) && Number(sort.system.sdspecial) > 0) {
      rollData.sdValue = Number(sort.system.sdspecial)
    }
    rollData.sortPointsAme = Number(sort.system.niveau)
    rollData.totalEsprit = 1
    if (sort.system.competence == "Grand Langage") {
      rollData.sortPointsAme *= 2
      rollData.totalEsprit = Math.floor((rollData.sortPointsAme) / 3)
    }
    if (rollData.sortPointsAme > this.system.magie.pointsame.value) {
      // Vérifier si au moins 1 point d'Esprit est disponible
      if (this.system.caracteristiques.esp.value <= rollData.totalEsprit) {
        ui.notifications.warn(`Pas assez de Points d'Esprit ni de Points d'Ame pour lancer ce sort (requis: ${rollData.totalEsprit}, disponible: ${this.system.caracteristiques.esp.value})`)
        return
      } else {
        rollData.spendEsprit = true
        ui.notifications.warn(`Vous n'avez pas assez de Points d'Ame pour lancer ce sort (requis: ${rollData.sortPointsAme}, disponible: ${this.system.magie.pointsame.value}).`)
        ui.notifications.warn(`${rollData.totalEsprit} Points d'Esprit seront utilisés à la place si vous effectuez le lancer.`)
      }
    }

    if (sort.system.carac2 != "none") {
      // get the best carac between carac1 and carac2
      if (this.system.caracteristiques[sort.system.carac1].value > this.system.caracteristiques[sort.system.carac2].value) {
        rollData.caracKey = sort.system.carac1
      } else {
        rollData.caracKey = sort.system.carac2
      }
      rollData.caracMessage = "Ce sort peut être lancé avec " + game.system.lesheritiers.config.caracList[sort.system.carac1] + " ou " + game.system.lesheritiers.config.caracList[sort.system.carac2] + ". La meilleure caractéristique a été selectionnée."
    } else {
      rollData.caracKey = sort.system.carac1
    }
    console.log("RollData", rollData)
    await HeritiersRollDialog.create(this, rollData)
  }


  /* -------------------------------------------- */
  async rollAttaqueArme(armeId) {
    let arme = this.items.get(armeId)
    if (arme) {
      arme = foundry.utils.duplicate(arme)
      arme.system.isMelee = HeritiersUtility.isArmeMelee(arme)
      let key = arme.system.isMelee ? "agi" : "prec"
      let rollData
      if (this.type == 'pnj') {
        rollData = this.getCommonRollData()
        rollData.competence = this._getCombattantCompetence()
      } else {
        let competenceName = arme.system.isMelee ? "Mêlée" : "Tir"
        rollData = this.getCommonRollData(undefined, competenceName)
      }
      rollData.carac = this.system.caracteristiques[key]
      rollData.caracKey = key
      rollData.arme = arme
      rollData.mode = "arme"
      rollData.attackType = "Attaque normale"
      rollData.armes = this.getOtherMeleeWeapons(arme)
      if (rollData.defenderTokenId && arme.system.isMelee) {
        rollData.cacheDifficulte = true
      }
      console.log(">>>> ARME", rollData)
      await HeritiersRollDialog.create(this, rollData)
    }
  }

  /* -------------------------------------------- */
  async rollAttaqueBrutaleArme(armeId) {
    let arme = this.items.get(armeId)
    if (arme) {
      let key = "for"
      arme.system.isMelee = HeritiersUtility.isArmeMelee(arme)
      let rollData
      if (this.type == 'pnj') {
        rollData = this.getCommonRollData()
        rollData.competence = this._getCombattantCompetence()
      } else {
        rollData = this.getCommonRollData(undefined, "Mêlée")
      }
      rollData.carac = this.system.caracteristiques[key]
      rollData.caracKey = key
      rollData.arme = foundry.utils.duplicate(arme)
      rollData.mode = "attaquebrutale"
      rollData.attackType = "Attaque brutale"
      rollData.armes = this.getOtherMeleeWeapons(arme)
      rollData.rulesMalus.push({ name: "Attaque brutale", value: -2 })
      await HeritiersRollDialog.create(this, rollData)
    }
  }
  /* -------------------------------------------- */
  async rollAttaqueChargeArme(armeId) {
    let arme = this.items.get(armeId)
    if (arme) {
      let key = "agi"
      arme.system.isMelee = HeritiersUtility.isArmeMelee(arme)
      let rollData
      if (this.type == 'pnj') {
        rollData = this.getCommonRollData()
        rollData.competence = this._getCombattantCompetence()
      } else {
        let pireCompetence = this.getPireCompetence("Mêlée", "Mouvement")
        rollData = this.getCommonRollData(undefined, pireCompetence.name)
      }
      rollData.carac = this.system.caracteristiques[key]
      rollData.caracKey = key
      rollData.arme = foundry.utils.duplicate(arme)
      rollData.armes = this.getOtherMeleeWeapons(arme)
      rollData.mode = "attaquecharge"
      rollData.attackType = "Attaque en charge"
      await HeritiersRollDialog.create(this, rollData)
    }
  }

  /* -------------------------------------------- */
  async rollAssomerArme(armeId) {
    let arme = this.items.get(armeId)
    if (arme) {
      let rollData
      if (this.type == 'pnj') {
        rollData = this.getCommonRollData()
        rollData.competence = this._getCombattantCompetence()
      } else {
        rollData = this.getCommonRollData(undefined, "Mêlée")
      }
      rollData.carac = this.system.caracteristiques["agi"]
      rollData.caracKey = "agi"
      rollData.arme = foundry.utils.duplicate(arme)
      rollData.mode = "assommer"
      rollData.attackType = "Assommer"
      if (rollData.defenderTokenId) {
        rollData.cacheDifficulte = true
      }
      await HeritiersRollDialog.create(this, rollData)
    }
  }

  /* -------------------------------------------- */
  pouvoirPassifDialog(pouvoir) {
    let rollData = this.getCommonRollData()
    rollData.pouvoir = pouvoir
    rollData.mode = "pouvoirpassif"
    rollData.pouvoirPointsUsage = 0
    rollData.noRoll = true

    let d = new Dialog({
      title: "Activer le pouvoir passif " + pouvoir.name,
      content: "<p>Choisissez le nombre de Points d'Usage</p>",
      buttons: {
        one: {
          icon: '<i class="fas fa-check"></i>',
          label: "1 Point d'Usage",
          callback: () => {
            rollData.pouvoirPointsUsage = 1;
            HeritiersUtility.rollHeritiers(rollData);
          }
        },
        two: {
          icon: '<i class="fas fa-check"></i>',
          label: "2 Points d'Usage",
          callback: () => {
            rollData.pouvoirPointsUsage = 2;
            HeritiersUtility.rollHeritiers(rollData);
          }
        },
        three: {
          icon: '<i class="fas fa-check"></i>',
          label: "3 Points d'Usage",
          callback: () => {
            rollData.pouvoirPointsUsage = 3;
            HeritiersUtility.rollHeritiers(rollData);
          }
        },
        four: {
          icon: '<i class="fas fa-check"></i>',
          label: "4 Points d'Usage",
          callback: () => {
            rollData.pouvoirPointsUsage = 4;
            HeritiersUtility.rollHeritiers(rollData);
          }
        },
        close: {
          icon: '<i class="fas fa-times"></i>',
          label: "Annuler",
          callback: () => {
          }
        }
      },
      default: "one",
      render: html => console.log("Pouvoir passif"),
      close: html => console.log("No option")
    });
    d.render(true);
  }

  /* -------------------------------------------- */
  async rollPouvoir(pouvoirId) {
    let pouvoir = this.items.get(pouvoirId)
    if (pouvoir) {
      if (pouvoir.system.pouvoirtype == "passif") {
        this.pouvoirPassifDialog(pouvoir)
        return
      }

      let rollData = this.getCommonRollData(undefined, undefined)

      rollData.pouvoirMaxUsage = this.getPouvoirUsageMax(pouvoir)
      rollData.pouvoir = foundry.utils.duplicate(pouvoir)
      rollData.mode = "pouvoir"

      if (pouvoir.system.feeriemasque != "autre") {
        rollData.pouvoirBase = foundry.utils.duplicate(this.system.rang[pouvoir.system.feeriemasque.toLowerCase()])
        rollData.pouvoirBase.label = "Féerie"
        if (pouvoir.system.istest && !pouvoir.system.carac) {
          ui.notifications.warn("Le pouvoir actif " + pouvoir.name + " n'a pas de caractéristique associée")
        }
        if (pouvoir.system.istest) {
          rollData.carac = foundry.utils.duplicate(this.system.caracteristiques[pouvoir.system.carac])
          rollData.caracKey = pouvoir.system.carac
        } else {
          rollData.noRoll = true
          HeritiersUtility.rollHeritiers(rollData);
          return;
          //this.incDecPointsUsage(pouvoir.id, -rollData.pouvoirPointsUsage)
          //ui.notifications.warn("Le pouvoir actif " + pouvoir.name + " a été utilisé, dépense de " + pouvoirPointsUsage + " points d'usage")
        }
      }
      await HeritiersRollDialog.create(this, rollData)
    }

  }

  /* -------------------------------------------- */
  incDecPointsAme(value) {
    let newValue = this.system.magie.pointsame.value + value
    newValue = Math.max(newValue, 0)
    newValue = Math.min(newValue, this.system.magie.pointsame.max)
    this.update({ 'system.magie.pointsame.value': newValue })
  }

  /* -------------------------------------------- */
  incDecPV(value) {
    let newValue = this.system.pv.value + value
    newValue = Math.max(newValue, 0)
    newValue = Math.min(newValue, this.system.pv.max)
    this.update({ 'system.pv.value': newValue })
  }

  /* -------------------------------------------- */
  incDecPointsUsage(pouvoirId, value) {
    let pouvoir = this.items.get(pouvoirId)
    let newValue = pouvoir.system.pointsusagecourant + value
    newValue = Math.max(newValue, 0)
    newValue = Math.min(newValue, this.getPouvoirUsageMax(pouvoir))
    this.updateEmbeddedDocuments('Item', [{ _id: pouvoirId, 'system.pointsusagecourant': newValue }])
  }

  /* -------------------------------------------- */
  getPouvoirUsage(pouvoirId) {
    let pouvoir = this.items.get(pouvoirId)
    return pouvoir.system.pointsusagecourant
  }

  /* -------------------------------------------- */
  getPouvoirUsageMax(pouvoir) {
    if (pouvoir.system.masquetype == "masque") {
      return this.system.rang.masque.value
    }
    return this.system.rang.feerie.value
  }
  /* -------------------------------------------- */
  recupUsage(value) {
    let updates = []
    for (let pouvoir of this.items) {
      if (pouvoir.type == "pouvoir") {
        let newValue = pouvoir.system.pointsusagecourant + value
        newValue = Math.max(newValue, 0)
        newValue = Math.min(newValue, this.getPouvoirUsageMax(pouvoir))
        updates.push({ _id: pouvoir.id, 'system.pointsusagecourant': newValue })
      }
    }
    if (updates.length > 0) {
      this.updateEmbeddedDocuments('Item', updates)
    }
  }
}
