/* -------------------------------------------- */
import { MournbladeCombat } from "./mournblade-combat.js";
import { MournbladeCommands } from "./mournblade-commands.js";

/* -------------------------------------------- */
export class MournbladeUtility {


  /* -------------------------------------------- */
  static async init() {
    Hooks.on('renderChatMessageHTML', (log, html, data) => MournbladeUtility.chatListeners(html))
    Hooks.on("getChatMessageContextOptions", (html, options) => MournbladeUtility.chatRollMenu(html, options))
    Hooks.on('renderChatMessageHTML', (message, html, data) => MournbladeUtility.chatMessageHandler(message, html, data))

    Hooks.on("getCombatTrackerEntryContext", (html, options) => {
      MournbladeUtility.pushInitiativeOptions(html, options);
    })

    this.rollDataStore = {}
    this.defenderStore = {}
    MournbladeCommands.init();

    Handlebars.registerHelper('count', function (list) {
      return list.length;
    })
    Handlebars.registerHelper('includes', function (array, val) {
      return array.includes(val);
    })
    Handlebars.registerHelper('upper', function (text) {
      return text.toUpperCase();
    })
    Handlebars.registerHelper('lower', function (text) {
      return text.toLowerCase()
    })
    Handlebars.registerHelper('upperFirst', function (text) {
      if (typeof text !== 'string') return text
      return text.charAt(0).toUpperCase() + text.slice(1)
    })
    Handlebars.registerHelper('notEmpty', function (list) {
      return list.length > 0;
    })
    Handlebars.registerHelper('mul', function (a, b) {
      return parseInt(a) * parseInt(b);
    })

  }
  /* -------------------------------------------- */
  static getActorFromRollData(rollData) {
    let actor = game.actors.get(rollData.actorId)
    if (rollData.tokenId) {
      let token = canvas.tokens.placeables.find(t => t.id == rollData.tokenId)
      if (token) {
        actor = token.actor
      }
    }
    return actor
  }

  /* -------------------------------------------- */
  static sortArrayObjectsByName(myArray) {
    myArray.sort((a, b) => {
      return a.name.localeCompare(b.name);
    })
  }

  /* -------------------------------------------- */
  static getAttributs() {
    return game.system.mournblade.config.attributs
  }
  /* -------------------------------------------- */
  static pushInitiativeOptions(html, options) {
  }

  /* -------------------------------------------- */
  static getSkills() {
    return this.skills
  }

  /* -------------------------------------------- */
  static async ready() {
    const skills = await MournbladeUtility.loadCompendium("fvtt-mournblade.skills")
    this.skills = skills.map(i => i.toObject())

    game.system.mournblade.config.listeNiveauSkill = MournbladeUtility.createDirectOptionList(0, 10)
    game.system.mournblade.config.listeNiveauCreature = MournbladeUtility.createDirectOptionList(0, 35)
    game.system.mournblade.config.modificateurOptions = MournbladeUtility.createArrayOptionList(-15, 15)
    game.system.mournblade.config.pointsAmeOptions = MournbladeUtility.createDirectOptionList(0, 20)
  }

  /* -------------------------------------------- */
  static async loadCompendiumData(compendium) {
    const pack = game.packs.get(compendium);
    return await pack?.getDocuments() ?? [];
  }

  /* -------------------------------------------- */
  static async loadCompendium(compendium, filter = item => true) {
    let compendiumData = await MournbladeUtility.loadCompendiumData(compendium);
    return compendiumData.filter(filter);
  }

  /* -------------------------------------------- */
  static getOptionsStatusList() {
    return this.optionsStatusList;
  }

  /* -------------------------------------------- */
  static getPredilection(comp, predIdx) {
    let pred = foundry.utils.duplicate(comp.system.predilections)
    return foundry.utils.duplicate(pred[predIdx] || { name: "Error!" })
  }

  /* -------------------------------------------- */
  static async chatMessageHandler(message, html, data) {
    const chatCard = $(html).find('.action-section')
    if (chatCard.length > 0) {
      // If the user is the message author or the actor owner, proceed
      const actor = game.actors.get(data.message.speaker.actor)
      // DEBUG : console.log("FOUND 1!!! ", actor, data.message)
      if (actor?.isOwner || game.user.isGM) {
        return
      }
      chatCard.hide()
    }
  }

  /* -------------------------------------------- */
  static async chatListeners(html) {

    $(html).on("click", '.predilection-reroll', async event => {
      let predIdx = $(event.currentTarget).data("predilection-index")
      let messageId = MournbladeUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      await actor.setPredilectionUsed(rollData.competence._id, predIdx)
      rollData.competence = foundry.utils.duplicate(actor.getCompetence(rollData.competence._id))
      rollData.predilectionUsed = MournbladeUtility.getPredilection(rollData.competence, predIdx)
      await MournbladeUtility.rollMournblade(rollData)
    })

    $(html).on("click", '.arme-roll-degats', async event => {
      let messageId = MournbladeUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "mournblade-roll")
      MournbladeUtility.rollDegatsFromAttaque(rollData)

    })

    $(html).on("click", '.arme-apply-degats', async event => {
      let messageId = MournbladeUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "mournblade-roll")
      if (game.user.isGM) {
        MournbladeUtility.applyDegatsFromAttaque(rollData)
      } else {
        game.socket.emit("system.fvtt-mournblade", { name: "msg_apply_damage", data: { rolLData: rollData } })
      }
    })
  }

  /* -------------------------------------------- */
  static async preloadHandlebarsTemplates() {

    const templatePaths = [
      'systems/fvtt-mournblade/templates/editor-notes-gm.html',
      'systems/fvtt-mournblade/templates/partial-item-description.html'
    ]
    return foundry.applications.handlebars.loadTemplates(templatePaths);
  }

  /* -------------------------------------------- */
  static removeChatMessageId(messageId) {
    if (messageId) {
      game.messages.get(messageId)?.delete();
    }
  }

  static findChatMessageId(current) {
    return MournbladeUtility.getChatMessageId(MournbladeUtility.findChatMessage(current));
  }

  static getChatMessageId(node) {
    return node?.attributes.getNamedItem('data-message-id')?.value;
  }

  static findChatMessage(current) {
    return MournbladeUtility.findNodeMatching(current, it => it.classList.contains('chat-message') && it.attributes.getNamedItem('data-message-id'))
  }

  static findNodeMatching(current, predicate) {
    if (current) {
      if (predicate(current)) {
        return current;
      }
      return MournbladeUtility.findNodeMatching(current.parentElement, predicate);
    }
    return undefined;
  }

  /* -------------------------------------------- */
  static createDirectOptionList(min, max) {
    let options = {};
    for (let i = min; i <= max; i++) {
      options[`${i}`] = `${i}`;
    }
    return options;
  }
  static createArrayOptionList(min, max) {
    let options = [];
    for (let i = min; i <= max; i++) {
      options.push({ key: `${i}`, label: `${i}` });
    }
    return options;
  }

  /* -------------------------------------------- */
  static getTarget() {
    if (game.user.targets && game.user.targets.size == 1) {
      for (let target of game.user.targets) {
        return target;
      }
    }
    return undefined;
  }

  /* -------------------------------------------- */
  static getRollData(id) {
    return this.rollDataStore[id];
  }

  /* -------------------------------------------- */
  static onSocketMesssage(msg) {
    if (msg.name == "msg_apply_damage") {
      if (game.user.isGM) {
        this.applyDegatsFromAttaque(msg.data.rollData);
      }
    }
  }

  /* -------------------------------------------- */
  static chatDataSetup(content, modeOverride, isRoll = false, forceWhisper) {
    let chatData = {
      user: game.user.id,
      rollMode: modeOverride || game.settings.get("core", "rollMode"),
      content: content
    };

    if (["gmroll", "blindroll"].includes(chatData.rollMode)) chatData["whisper"] = ChatMessage.getWhisperRecipients("GM").map(u => u.id);
    if (chatData.rollMode === "blindroll") chatData["blind"] = true;
    else if (chatData.rollMode === "selfroll") chatData["whisper"] = [game.user];

    if (forceWhisper) { // Final force !
      chatData["speaker"] = ChatMessage.getSpeaker();
      chatData["whisper"] = ChatMessage.getWhisperRecipients(forceWhisper);
    }

    return chatData;
  }

  /* -------------------------------------------- */
  static async showDiceSoNice(roll, rollMode) {
    if (game.modules.get("dice-so-nice")?.active) {
      if (game.dice3d) {
        let whisper = null;
        let blind = false;
        rollMode = rollMode ?? game.settings.get("core", "rollMode");
        switch (rollMode) {
          case "blindroll": //GM only
            blind = true;
          case "gmroll": //GM + rolling player
            whisper = this.getUsers(user => user.isGM);
            break;
          case "roll": //everybody
            whisper = this.getUsers(user => user.active);
            break;
          case "selfroll":
            whisper = [game.user.id];
            break;
        }
        await game.dice3d.showForRoll(roll, game.user, true, whisper, blind);
      }
    }
  }

  /* -------------------------------------------- */
  static computeResult(rollData) {
    if (rollData.mainDice == "1d20") {
      let diceValue = rollData.roll.terms[0].results[0].result
      diceValue *= (rollData.doubleD20) ? 2 : 1
      //console.log("PAIR/IMP", diceValue)
      if (diceValue % 2 == 1) {
        //console.log("PAIR/IMP2", diceValue)
        rollData.finalResult -= rollData.roll.terms[0].results[0].result // Substract value
        if (diceValue == 1 || diceValue == 11) {
          rollData.isDramatique = true
          rollData.isSuccess = false
        }
      }
    }
    this.computeQualityResult(rollData)
  }

  /* -------------------------------------------- */
  static computeQualityResult(rollData) {
    //console.log("Result : ", rollData)
    if (rollData.difficulte > 0 && !rollData.isDramatique) {
      rollData.isSuccess = (rollData.finalResult >= rollData.difficulte)
      rollData.isHeroique = ((rollData.finalResult - rollData.difficulte) >= 10)
      rollData.isDramatique = ((rollData.finalResult - rollData.difficulte) <= -10)
      rollData.isPureSuccess = (rollData.isSuccess && !rollData.isHeroique)
    }
  }

  /* -------------------------------------------- */
  static async rollMournblade(rollData) {

    let actor = MournbladeUtility.getActorFromRollData(rollData)
    if (rollData.attrKey == "tochoose") { // No attr selected, force address
      rollData.attrKey = "adr"
    }
    if (!rollData.attr) {
      rollData.actionImg = "systems/fvtt-mournblade/assets/icons/" + actor.system.attributs[rollData.attrKey].labelnorm + ".webp"
      rollData.attr = foundry.utils.duplicate(actor.system.attributs[rollData.attrKey])
    }

    rollData.diceFormula = rollData.mainDice
    if (rollData.doubleD20) { // Multiply result !
      rollData.diceFormula += "*2"
      if (!rollData.isReroll) {
        actor.changeEclat(-1)
      }
    }
    //console.log("BEFORE COMP", rollData)
    if (rollData.competence) {
      rollData.predilections = foundry.utils.duplicate(rollData.competence.system.predilections)
      let compmod = (rollData.competence.system.niveau == 0) ? -3 : 0
      rollData.diceFormula += `+${rollData.attr.value}+${rollData.competence.system.niveau}+${rollData.modificateur}+${compmod}`
    } else {
      rollData.diceFormula += `+${rollData.attr.value}*2+${rollData.modificateur}`
    }
    rollData.diceFormula += `+${rollData.malusSante}+${rollData.malusAme}`

    if (rollData.arme?.type == "arme") {
      rollData.diceFormula += `+${rollData.arme.system.bonusmaniementoff}`
    }

    // Apply modifiers
    for (let modifier of rollData.modifiers) {
      if (modifier.system.modifiertype == "roll" && modifier.system.apply) {
        rollData.diceFormula += `+${modifier.system.value}`
      }
    }
    // Apply desavantages
    let desavantagesBonus = 0
    for (let desavantage in rollData.desavantages) {
      if (rollData.desavantages[desavantage]) {
        desavantagesBonus += 5
      }
    }
    desavantagesBonus = Math.min(15, desavantagesBonus)
    rollData.diceFormula += `+${desavantagesBonus}`

    // Monté ?
    if (rollData.isMonte) {
      rollData.diceFormula += "+5"
    }

    // Specific modifier for distance
    if (rollData.arme?.system?.isDistance) {
      if (rollData.visee) {
        rollData.diceFormula += "+5"
      }
      if (rollData.cibleconsciente) {
        rollData.diceFormula += `-${rollData.defender.system.attributs.adr.value}`
      }
      if (rollData.ciblecourt) {
        if (rollData.difficulte <= 15) { // Portée courte ou moins
          rollData.diceFormula += `-5`
        } else {
          rollData.diceFormula += `-10`
        }
      }
      if (rollData.typeCouvert != "aucun") {
        rollData.diceFormula += `+${rollData.config.couverts[rollData.typeCouvert].value}`
      }
    }

    if (rollData.rune) {
      rollData.runeduree = Math.ceil((rollData.runeame + 3) / 3)
      if (rollData.runemode == "inscrire") {
        rollData.runeduree *= 2
      }
      if (rollData.runemode == "prononcer") {
        rollData.runeduree = 1
      }
    }

    let myRoll = await new Roll(rollData.diceFormula).evaluate();
    await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
    rollData.roll = foundry.utils.duplicate(myRoll)
    rollData.diceResult = myRoll.terms[0].results[0].result
    console.log(">>>> ", myRoll)

    rollData.finalResult = myRoll.total
    this.computeResult(rollData)

    // Application immédiate selon type de jet
    if (rollData.rune) {
      let subAme = rollData.runeame
      if (rollData.isEchec && !rollData.isDramatique) {
        subAme = Math.ceil((subAme + 1) / 2)
      }
      actor.subPointsAme(rollData.runemode, subAme)
    }
    if (rollData.typeAttaque == "assomer" && rollData.defenderTokenId && rollData.isPureSuccess) {
      let defender = game.canvas.tokens.get(rollData?.defenderTokenId)?.actor
      defender.setModifier("Assomer : Prochaine action", "roll", -5)
    }
    if (rollData.typeAttaque == "fuir" && rollData.difficulte > 0 && !rollData.isSuccess) {
      actor.setModifier("Fuite échouée : -5 en défense ce round et suivant", "defense", -5)
    }
    if (rollData.typeAttaque == "immobiliser" && rollData.difficulte > 0 && rollData.isPureSuccess) {
      actor.setModifier("Immobilisation en cours : -5 pour prochaine action", "roll", -5)
    }
    if (rollData.typeAttaque == "chargecavalerie") {
      actor.setModifier("Charge de Cavalerie : -5 défense pour le tour", "defense", -5)
    }
    this.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-mournblade/templates/chat-generic-result.html`, rollData)
    }, rollData)

  }

  /* -------------------------------------------- */
  static async rollDegatsFromAttaque(rollData) {
    let maximize = false
    let degatsMessage = "Degats normaux"

    if (rollData.arme?.system?.isMelee) {
      rollData.degatsFormula = rollData.arme.system.totalDegats
      if (rollData.isHeroique) { // Deux fois les dés de dégats
        degatsMessage = "Dégats doublés"
      }

      if (rollData.typeAttaque == "assomer") {
        rollData.degatsFormula = false
      }

      if (rollData.typeAttaque == "charger") {
        rollData.degatsFormula += "+2"
      }
      if (rollData.typeAttaque == "chargecavalerie") {
        rollData.degatsFormula += "+5"
      }

      if (rollData.typeAttaque == "precise") {
        degatsMessage = "Degats normaux"
        if (rollData.isHeroique) { // Degats max
          maximize = true
          degatsMessage = "Dégats maximaux, ignore l'armure du défenseur";
          rollData.ignoreDefenseArmor = true
        }
      }
      if (rollData.typeAttaque == "feinte") {
        degatsMessage = "Pas de dégats, mais bonus pour prochaine attaque"
        rollData.degatsFormula = false
        rollData.nextBonus = 5
        if (rollData.isHeroique) { // Bonus pour prochaine action
          rollData.nextBonus = 10
          rollData.nextBonusDegats = 10
        }
      }
      if (rollData.typeAttaque == "coupbas") {
        degatsMessage = "Pas de dégats, mais malus pour prochaine action complexe du défenseur"
        rollData.degatsFormula = false
        rollData.nextMalus = 5
        if (rollData.isHeroique) { // Malus pour prochaine action
          rollData.nextMalus = 15
        }
      }
      if (rollData.typeAttaque == "contenir") {
        degatsMessage = "Pas de dégats, mais l'adversaire ne peut pas vous attaquer pour le reste du tour"
        rollData.degatsFormula = false
        if (rollData.isHeroique) { // Malus pour prochaine action
          degatsMessage = "Pas de dégats, mais tout les adversaires avec une défense inférieure ou égale à " + rollData.finalResult - 10 +
            " ne peuvent pas vous attaquer pour le reste du tour"
        }
      }
      if (rollData.typeAttaque == "desarmer") {
        degatsMessage = "Pas de dégats, mais l'adversaire reçoit un malus de -5 pour sa prochaine action"
        rollData.degatsFormula = false
        if (rollData.isHeroique) { // Malus pour prochaine action
          rollData.defenderDesarme = true
          degatsMessage = "Pas de dégats, mais l'arme de votre adversaire est arrachée de ses mains"
        }
      }
    } else { // Armes à distance
      rollData.degatsFormula = rollData.arme.system.totalDegats
    }

    // Perform the roll, show the dice
    rollData.finalResult = 0
    rollData.degatsMessage = degatsMessage
    if (rollData.degatsFormula) {
      console.log("Degats formula", rollData.degatsFormula)
      // Twice!maximize
      if (rollData.isHeroique && !maximize) {
        rollData.degatsFormula += "+" + rollData.degatsFormula
      }
      // Latest modifiers
      for (let mod of rollData.modifiers) {
        if (mod.system.modifiertype == "degats") {
          rollData.degatsFormula += `+${mod.system.value}`
        }
      }
      let degatsRoll = await new Roll(rollData.degatsFormula).evaluate({ maximize: maximize })
      await this.showDiceSoNice(degatsRoll, game.settings.get("core", "rollMode"))
      rollData.degatsRoll = foundry.utils.duplicate(degatsRoll)
      rollData.finalResult = degatsRoll.total
    }

    this.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-mournblade/templates/chat-degats-result.html`, rollData)
    }, rollData)

  }

  /* -------------------------------------------- */
  static applyDegatsFromAttaque(rollData) {
    let defender = game.canvas.tokens.get(rollData?.defenderTokenId)?.actor
    if (defender && rollData.arme) {
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      if (rollData.typeAttaque == "desarmer" && !rollData.isHeroique) {
        defender.setModifier("Malus suite à désarmement", "roll", -5)
      }
      if (rollData.typeAttaque == "charger") {
        actor.setModifier("Défense suite à charge", "roll", -5)
      }
      if (rollData.nextBonus) {
        actor.setModifier("Prochaine attaque", "roll", rollData.nextBonus)
        if (rollData.nextDegatsBonus) {
          actor.setModifier("Prochaine attaque", "degats", rollData.nextDegatsBonus)
        }
      }
      if (rollData.nextMalus) {
        defender.setModifier("Prochaine action complexe", "roll", -rollData.nextMalus)
      }
      if (rollData.defenderDesarme) {
        ui.notifications.info("L'arme de " + defender.name + " est arrachée de ses mains (à gérer manuellement)")
      }
      let degats = rollData.finalResult

      let type = (rollData.arme.system.nonletaux) ? "nonletaux" : "letaux"
      if (rollData.arme.system.ignorearmure) {
        rollData.ignoreDefenseArmor = true
      }
      defender.incDecSante(type, +degats, rollData.ignoreDefenseArmor)
      ui.notifications.info(defender.name + "a subi " + degats + " points de santé " + type + ".")
    } else {
      ui.notifications.warn("Pas de cible sélectionnée ou pas d'arme de défense équipée.")
    }
  }

  /* -------------------------------------------- */
  static async bonusRollMournblade(rollData) {
    rollData.bonusFormula = rollData.addedBonus

    let bonusRoll = await new Roll(rollData.bonusFormula).evaluate()
    await this.showDiceSoNice(bonusRoll, game.settings.get("core", "rollMode"));
    rollData.bonusRoll = foundry.utils.duplicate(bonusRoll)

    rollData.finalResult += rollData.bonusRoll.total

    this.computeQualityResult(rollData)

    this.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-mournblade/templates/chat-generic-result.html`, rollData)
    }, rollData)

  }

  /* -------------------------------------------- */
  static getUsers(filter) {
    return game.users.filter(filter).map(user => user._id);
  }

  /* -------------------------------------------- */
  static getWhisperRecipients(rollMode, name) {
    switch (rollMode) {
      case "blindroll": return this.getUsers(user => user.isGM);
      case "gmroll": return this.getWhisperRecipientsAndGMs(name);
      case "selfroll": return [game.user.id];
    }
    return undefined;
  }
  /* -------------------------------------------- */
  static getWhisperRecipientsAndGMs(name) {
    let recep1 = ChatMessage.getWhisperRecipients(name) || [];
    return recep1.concat(ChatMessage.getWhisperRecipients('GM'));
  }

  /* -------------------------------------------- */
  static blindMessageToGM(chatOptions) {
    let chatGM = foundry.utils.duplicate(chatOptions);
    chatGM.whisper = this.getUsers(user => user.isGM);
    chatGM.content = "Blinde message of " + game.user.name + "<br>" + chatOptions.content;
    console.log("blindMessageToGM", chatGM);
    game.socket.emit("system.fvtt-weapons-of-the-gods", { msg: "msg_gm_chat_message", data: chatGM });
  }

  /* -------------------------------------------- */
  static async searchItem(dataItem) {
    let item;
    if (dataItem.pack) {
      item = await fromUuid("Compendium." + dataItem.pack + "." + dataItem.id);
    } else {
      item = game.items.get(dataItem.id)
    }
    return item
  }

  /* -------------------------------------------- */
  static split3Columns(data) {

    let array = [[], [], []];
    if (data == undefined) return array;

    let col = 0;
    for (let key in data) {
      let keyword = data[key];
      keyword.key = key; // Self-reference
      array[col].push(keyword);
      col++;
      if (col == 3) col = 0;
    }
    return array;
  }

  /* -------------------------------------------- */
  static async createChatMessage(name, rollMode, chatOptions, rollData = undefined) {
    switch (rollMode) {
      case "blindroll": // GM only
        if (!game.user.isGM) {
          this.blindMessageToGM(chatOptions);

          chatOptions.whisper = [game.user.id];
          chatOptions.content = "Message only to the GM";
        }
        else {
          chatOptions.whisper = this.getUsers(user => user.isGM);
        }
        break;
      default:
        chatOptions.whisper = this.getWhisperRecipients(rollMode, name);
        break;
    }
    chatOptions.alias = chatOptions.alias || name;
    chatOptions.speaker = ChatMessage.getSpeaker();
    let msg = await ChatMessage.create(chatOptions)
    console.log("=======>", rollData)
    msg.setFlag("world", "mournblade-roll", rollData)
  }

  /* -------------------------------------------- */
  static getBasicRollData() {
    let rollData = {
      rollId: foundry.utils.randomID(16),
      rollMode: game.settings.get("core", "rollMode"),
      difficulte: 0,
      modificateur: 0,
      config: foundry.utils.duplicate(game.system.mournblade.config),
    }
    MournbladeUtility.updateWithTarget(rollData)
    return rollData
  }

  /* -------------------------------------------- */
  static updateWithTarget(rollData) {
    let target = MournbladeUtility.getTarget()
    if (target) {
      rollData.defenderTokenId = target.id
      let defender = game.canvas.tokens.get(rollData.defenderTokenId).actor
      rollData.defenderCombatValues = defender.getCombatValues()
      rollData.defender = defender.toObject() // Simpler
      rollData.defenderDefense = defender.getBestDefenseValue()
      rollData.armeDefense = defender.getBestDefenseValue()
      if (rollData.armeDefense) {
        rollData.difficulte = rollData.armeDefense.system.totalDefensif
      } else {
        ui.notifications.warn("Aucune arme de défense équipée, difficulté manuelle à positionner.")
      }
    }
  }

  /* -------------------------------------------- */
  static createChatWithRollMode(name, chatOptions, rollData = undefined) {
    this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions, rollData)
  }

  /* -------------------------------------------- */
  static applyBonneAventureRoll(li, changed, addedBonus) {
    let msgId = $(li).data("message-id")
    let msg = game.messages.get(msgId)
    if (msg) {
      let rollData = msg.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      actor.changeBonneAventure(changed)
      rollData.isReroll = true
      rollData.textBonus = "Bonus de Points d'Aventure"
      if (addedBonus == "reroll") {
        MournbladeUtility.rollMournblade(rollData)
      } else {
        rollData.addedBonus = addedBonus
        MournbladeUtility.bonusRollMournblade(rollData)
      }
    }
  }

  /* -------------------------------------------- */
  static applyEclatRoll(li, changed, addedBonus) {
    let msgId = $(li).data("message-id")
    let msg = game.messages.get(msgId)
    if (msg) {
      let rollData = msg.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      actor.changeEclat(changed)
      rollData.isReroll = true
      rollData.textBonus = "Bonus d'Eclat"
      rollData.addedBonus = addedBonus
      MournbladeUtility.bonusRollMournblade(rollData)
    }
  }

  /* -------------------------------------------- */
  static chatRollMenu(html, options) {
    let canApply = li => canvas.tokens.controlled.length && li.find(".mournblade-roll").length
    let canApplyBALoyal = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      return (!rollData.isReroll && actor.getBonneAventure() > 0 && actor.getAlignement() == "loyal")
    }
    let canApplyPELoyal = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      return (!rollData.isReroll && actor.getEclat() > 0 && actor.getAlignement() == "loyal")
    }
    let canApplyBAChaotique = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      return (!rollData.isReroll && actor.getBonneAventure() > 0 && actor.getAlignement() == "chaotique")
    }
    let canApplyBAChaotique3 = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      return (!rollData.isReroll && actor.getBonneAventure() > 2 && actor.getAlignement() == "chaotique")
    }
    let canApplyPEChaotique = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      return (!rollData.isReroll && actor.getEclat() > 0 && actor.getAlignement() == "chaotique")
    }
    let hasPredilection = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      if (rollData.competence) {
        let nbPred = rollData.competence.system.predilections.filter(pred => !pred.used).length
        return (!rollData.isReroll && rollData.competence && nbPred > 0)
      }
      return false
    }
    let canCompetenceDouble = function (li) {
      let message = game.messages.get($(li).attr("data-message-id"))
      let rollData = message.getFlag("world", "mournblade-roll")
      let actor = MournbladeUtility.getActorFromRollData(rollData)
      if (rollData.competence) {
        return rollData.competence.system.doublebonus
      }
      return false
    }
    options.push(
      {
        name: "Ajouer +3 (1 point de Bonne Aventure)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyBALoyal,
        callback: li => MournbladeUtility.applyBonneAventureRoll(li, -1, "+3")
      }
    )
    options.push(
      {
        name: "Ajouer +6 (1 point de Bonne Aventure)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyBALoyal && canCompetenceDouble,
        callback: li => MournbladeUtility.applyBonneAventureRoll(li, -1, "+6")
      }
    )
    options.push(
      {
        name: "Ajouer +1d6 (1 point de Bonne Aventure)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyBAChaotique,
        callback: li => MournbladeUtility.applyBonneAventureRoll(li, -1, "+1d6")
      }
    )
    options.push(
      {
        name: "Ajouer +2d6 (1 point de Bonne Aventure)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyBAChaotique && canCompetenceDouble,
        callback: li => MournbladeUtility.applyBonneAventureRoll(li, -1, "+2d6")
      }
    )
    options.push(
      {
        name: "Relancer le dé (3 points de Bonne Aventure)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyBAChaotique3,
        callback: li => MournbladeUtility.applyBonneAventureRoll(li, -3, "reroll")
      }
    )
    options.push(
      {
        name: "Ajouter +10 (1 Point d'Eclat)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyPELoyal,
        callback: li => MournbladeUtility.applyEclatRoll(li, -1, "+10")
      }
    )
    options.push(
      {
        name: "Ajouter +20 (1 Point d'Eclat)",
        icon: "<i class='fas fa-user-plus'></i>",
        condition: canApply && canApplyPELoyal && canCompetenceDouble,
        callback: li => MournbladeUtility.applyEclatRoll(li, -1, "+20")
      }
    )
    return options
  }

  /* -------------------------------------------- */
  static async confirmDelete(actorSheet, li) {
    let itemId = li.data("item-id");
    let msgTxt = "<p>Voulez vous supprimer cet item ?";
    let buttons = {
      delete: {
        icon: '<i class="fas fa-check"></i>',
        label: "Oui !",
        callback: () => {
          actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
          li.slideUp(200, () => actorSheet.render(false));
        }
      },
      cancel: {
        icon: '<i class="fas fa-times"></i>',
        label: "Non !"
      }
    }
    msgTxt += "</p>";
    let d = new Dialog({
      title: "Confirmer la suppression",
      content: msgTxt,
      buttons: buttons,
      default: "cancel"
    });
    d.render(true);
  }

}