/* -------------------------------------------- */

/* -------------------------------------------- */
const ECRYME_WELCOME_MESSAGE_URL = "https://www.uberwald.me/gitea/public/fvtt-te-deum/raw/branch/main/welcome-message-tedeum.html"

export class TeDeumUtility {

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

    CONFIG.Actor.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
    CONFIG.Item.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
    CONFIG.Scene.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
    CONFIG.JournalEntry.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
    CONFIG.Macro.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
    CONFIG.Adventure.compendiumBanner = "systems/fvtt-te-deum/images/ui/compendium_banner.webp"
  }

  static installHooks() {
    Hooks.on('renderChatMessageHTML', (message, html) => {
      TeDeumUtility.chatListeners(html);
      TeDeumUtility.onRenderChatMessage(message, html);
    });

    Hooks.on("renderActorDirectory", (app, html, data) => {
      if (game.user.can('ACTOR_CREATE')) {
        const button = document.createElement('button');
        button.style.width = '60%';
        button.classList.add('tedeum-create-character');
        button.innerHTML = 'Créer un Personnage'
        button.addEventListener('click', () => {
          let cr = new game.system.tedeum.TeDeumCharacterCreator();
          cr.init()
        })
        $(html).find('.header-actions').after(button)
      }
    })

    Hooks.on("combatStart", async (combat, updateData, options) => {
      this.resetCombatActions(combat)
    });

    Hooks.on("combatRound", (combat, updateData, updateOptions) => {
      // List all actors related to combatant
      if (game.user.isGM) {
        this.resetCombatActions(combat)
      }
    })

    Hooks.on("getCombatTrackerContextOptions", (html, options) => {
      console.log("Get Combat Tracker Context", html, options)
      this.pushCombatOptions(html, options);
    });

  }

  /* -------------------------------------------- */
  static pushCombatOptions(html, options) {
    options.push({ name: "Actions +1", condition: true, icon: '<i class="fas fa-plus"></i>', callback: target => { game.combat.modifyAction($(target).data('combatant-id'), 1); } })
    options.push({ name: "Actions -1", condition: true, icon: '<i class="fas fa-minus"></i>', callback: target => { game.combat.modifyAction($(target).data('combatant-id'), -1); } })
    options.push({ name: "Actions MG +1", condition: true, icon: '<i class="fas fa-plus"></i>', callback: target => { game.combat.modifyAction($(target).data('combatant-id'), 1, true); } })
    options.push({ name: "Actions MG -1", condition: true, icon: '<i class="fas fa-minus"></i>', callback: target => { game.combat.modifyAction($(target).data('combatant-id'), -1, true); } })
  }

  /* -------------------------------------------- */
  static async resetCombatActions(combat) {
    if (game.user.isGM) {
      for (let c of combat.combatants) {
        let actor = game.actors.get(c.actorId)
        if (actor) {
          let nbActions = actor.getNbActions()?.value || 0
          let isMainGauche = (actor.getCompetenceScore("Main gauche") > 0)
          let nbActionsMainGauche = isMainGauche ? nbActions : 0
          await c.setFlag("world", "available-actions", { nbActions, nbActionsMainGauche })
          await c.update({ name: `${c.token.name} (${nbActions} / ${nbActionsMainGauche})` })
        }
      }
    }
  }

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

    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);
    })
    Handlebars.registerHelper('add', function (a, b) {
      return parseInt(a) + parseInt(b);
    })
    Handlebars.registerHelper('valueAtIndex', function (arr, idx) {
      return arr[idx];
    })
    Handlebars.registerHelper('for', function (from, to, incr, block) {
      let accum = '';
      for (let i = from; i <= to; i += incr)
        accum += block.fn(i);
      return accum;
    })
    Handlebars.registerHelper('getConfigLabel', function (configName, key) {
      //console.log("getConfigLabel", configName, key)
      return game.system.tedeum.config[configName][key].label
    })
    Handlebars.registerHelper('getConfigLabelArray', function (configName, key) {
      //console.log("getConfigLabel", configName, key)
      return game.system.tedeum.config[configName][key].label
    })
    Handlebars.registerHelper('isSpecArmeType', function (key, armeType) {
      return game.system.tedeum.config.ARME_SPECIFICITE[key][armeType]
    })

    Handlebars.registerHelper('getConfigLabelWithGender', function (configName, key, genderKey) {
      return game.system.tedeum.config[configName][key]["label" + genderKey]
    })
    Handlebars.registerHelper('getCaracDescription', function (key, value) {
      return game.system.tedeum.config.descriptionValeur[Number(value)][key]
    })
    Handlebars.registerHelper('getEducationEtape', function (key) {
      return game.system.tedeum.config.etapesEducation[key].label
    })

    Handlebars.registerHelper('isGM', function () {
      return game.user.isGM
    })
    Handlebars.registerHelper('monnaie', function (value) {
      let monnaie = game.system.tedeum.config.monnaieUnit[String(value)]
      if (monnaie) {
        return monnaie.label
      }
      return value
    })
    // Handle v12 removal of this helper
    Handlebars.registerHelper('select', function (selected, options) {
      const escapedValue = RegExp.escape(Handlebars.escapeExpression(selected));
      const rgx = new RegExp(' value=[\"\']' + escapedValue + '[\"\']');
      const html = options.fn(this);
      return html.replace(rgx, "$& selected");
    });


    // Load compendium data
    const competences = await TeDeumUtility.loadCompendium("fvtt-te-deum.competences")
    this.competences = competences.map(i => i.toObject())
    this.competencesList = {}
    for (let i of this.competences) {
      this.competencesList[i.name.toLowerCase()] = { name: i.name, id: i._id }
    }
    this.competencesList = Object.entries(this.competencesList).sort().reduce((o, [k, v]) => (o[k] = v, o), {})
  }

  /* -------------------------------------------- */
  static async importDefaultScene() {
    let exists = game.scenes.find(j => j.name == "Te Deum");
    if (!exists) {
      const scenes = await TeDeumUtility.loadCompendium("fvtt-te-deum.scenes")
      let newDocuments = scenes.filter(i => i.name == "Te Deum");
      if (newDocuments) {
        await game.scenes.documentClass.create(newDocuments);
        game.scenes.find(i => i.name == "Te Deum").activate();
      }
    }
  }

  /* -------------------------------------------- */
  static welcomeMessage() {
    if (game.user.isGM) {
      // Try to fetch the welcome message from the github repo "welcome-message-ecryme.html"
      fetch(ECRYME_WELCOME_MESSAGE_URL)
        .then(response => response.text())
        .then(html => {
          ChatMessage.create({
            user: game.user.id,
            whisper: [game.user.id],
            content: html
          });
        })
        .catch(error => {
          console.error("Error fetching welcome message:", error);
          ChatMessage.create({
            user: game.user.id,
            whisper: [game.user.id],
            content: "<b>Bienvenue dans Ecryme RPG !</b><br>Visitez le site officiel pour plus d'informations."
          });
        });
    }
  }

  /*-------------------------------------------- */
  static getCompetences() {
    return this.competences
  }
  /*-------------------------------------------- */
  static getCompetencesForDropDown() {
    return this.competencesList
  }

  /*-------------------------------------------- */
  static prepareEducationContent(formData) {
    let etape = game.system.tedeum.config.etapesEducation[formData.system.etape]
    let nbCompetences = etape.nbCompetences
    for (let key in formData.system.competences) {
      formData.system.competences[key].valid = false
    }
    for (let i = 1; i <= nbCompetences; i++) {
      formData.system.competences[`comp${i}`].valid = true
    }
    let nbCaracteristiques = etape.nbCaracteristiques
    for (let key in formData.system.caracteristiques) {
      formData.system.caracteristiques[key].valid = false
    }
    for (let i = 1; i <= nbCaracteristiques; i++) {
      formData.system.caracteristiques[`carac${i}`].valid = true
    }
    formData.hasQuestionnaire = etape.hasQuestionnaire;
    formData.hasMultiplier = etape.hasMultiplier;
    formData.hasDebouches = etape.hasDebouches;
    formData.canCompetencesOpt = etape.canCompetencesOpt;
    formData.hasGenre = etape.hasGenre;
  }

  /*-------------------------------------------- */
  static upperFirst(text) {
    if (typeof text !== 'string') return text
    return text.charAt(0).toUpperCase() + text.slice(1)
  }

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

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

  /* -------------------------------------------- */
  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 async manageOpposition(rollData) {
    if (!this.currentOpposition) {
      // Store rollData as current GM opposition
      this.currentOpposition = rollData
      ui.notifications.info("Opposition démarrée avec " + rollData.alias);
    } else {
      // Perform the opposition
      let isAttackWinner = true
      let rWinner, rLooser
      if (this.currentOpposition.total <= rollData.total) {
        rWinner = foundry.utils.duplicate(rollData)
        rLooser = foundry.utils.duplicate(this.currentOpposition)
        isAttackWinner = false
      } else {
        rWinner = foundry.utils.duplicate(this.currentOpposition)
        rLooser = foundry.utils.duplicate(rollData)
        isAttackWinner = true
      }
      this.currentOpposition = undefined // Reset opposition
      let oppositionData = {
        winner: rWinner,
        looser: rLooser
      }
      // Update difficulty
      rWinner.difficulty = rLooser.total
      rLooser.difficulty = rWinner.total
      await this.computeResults(rWinner)
      await this.computeResults(rLooser)
      // Auto XP management when opposed
      if (rWinner.isReussiteCritique) {
        let actor = this.getActorFromRollData(rWinner)
        actor.modifyXP(rWinner.carac.key, 1)
      }
      if (rLooser.isEchecCritique) {
        let actor = this.getActorFromRollData(rLooser)
        actor.modifyXP(rLooser.carac.key, 1)
      }

      let msg = await this.createChatWithRollMode(rollData.alias, {
        content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-te-deum/templates/chat/chat-opposition-result.hbs`, oppositionData)
      })
      await msg.setFlag("world", "te-deum-rolldata", rollData)

      // Si le gagnant est l'attaquant, appliquer les dégats sur la victime
      if (isAttackWinner && rWinner.isSuccess && rWinner.mode == "arme" && rWinner.arme?.system.typeArme == "melee" && rWinner.defenderTokenId) {
        await this.appliquerDegats(rWinner)
      }

      console.log("Opposition result", rollData, isAttackWinner, oppositionData)
    }
  }

  /* -------------------------------------------- */
  static getTokenActorFromId(tokenId) {
    for (let scene of game.scenes) {
      const tokenDoc = scene.tokens.get(tokenId)
      if (tokenDoc) return tokenDoc.actor
    }
    return null
  }

  /* -------------------------------------------- */
  static async appliquerDegats(rollData) {
    await this.processAttaqueMelee(rollData)
    let defenderActor = this.getTokenActorFromId(rollData.defenderTokenId)
    if (defenderActor) {
      if (game.user.isGM || defenderActor.isOwner) {
        await defenderActor.appliquerDegats(rollData)
      } else {
        // Send a socket message — seul le premier MJ actif le traitera
        game.socket.emit("system.fvtt-te-deum", { name: "msg_apply_damage", data: { rollData } });
      }
      // Attaque naturelle avec dégats inférieur à -2
      if ((rollData?.arme?.system.specificites?.poing?.hasSpec || rollData?.arme?.system.specificites?.pied?.hasSpec) && rollData.degats < -2) {
        let attacker = this.getActorFromRollData(rollData)
        attacker.appliquerBlessure("estafilade", "maindroite", "Contusion suite à une attaque naturelle")
        ui.notifications.info(`${attacker.name} subit 1 contusion en infligeant ${rollData.degats} dégâts à mains nues`)
      }
    } else {
      ui.notifications.error("Impossible de trouver la cible de l'attaque, aucun degats appliqué")
    }
  }

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

    $(html).on("click", '.chat-command-opposition', event => {
      let messageId = TeDeumUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "te-deum-rolldata")
      if (rollData) {
        TeDeumUtility.manageOpposition(rollData, messageId)
      }
    })
    $(html).on("click", '.chat-command-appliquer-degats', event => {
      let messageId = TeDeumUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "te-deum-rolldata")
      if (rollData) {
        TeDeumUtility.appliquerDegats(rollData, messageId)
      }
    })
    $(html).on("click", '.chat-command-gain-xp', async event => {
      let messageId = TeDeumUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "te-deum-rolldata")
      if (rollData) {
        let actor = TeDeumUtility.getActorFromRollData(rollData)
        actor.modifyXP(rollData.carac.key, 1)
        event.currentTarget.style.display = 'none'; // feedback immédiat local
        await message.setFlag("world", "te-deum-xp-used", true) // sync tous les clients
      }
    })
  }

  /* -------------------------------------------- */
  static onRenderChatMessage(message, html) {
    if (message.getFlag("world", "te-deum-xp-used")) {
      const btn = html.querySelector('.chat-command-gain-xp');
      if (btn) btn.style.display = 'none';
    }
  }

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

    const templatePaths = [
      'systems/fvtt-te-deum/templates/actors/editor-notes-gm.hbs',
      'systems/fvtt-te-deum/templates/items/partial-item-nav.hbs',
      'systems/fvtt-te-deum/templates/items/partial-item-description.hbs',
      'systems/fvtt-te-deum/templates/dialogs/partial-creator-status.hbs',
      'systems/fvtt-te-deum/templates/items/item-arme-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-armure-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-blessure-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-competence-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-education-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-equipement-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-grace-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-maladie-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-origine-sheet.hbs',
      'systems/fvtt-te-deum/templates/items/item-simple-sheet.hbs',
    ]
    return foundry.applications.handlebars.loadTemplates(templatePaths);
  }

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

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

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

  static findChatMessage(current) {
    return TeDeumUtility.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 TeDeumUtility.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 buildListOptions(min, max) {
    let options = ""
    for (let i = min; i <= max; i++) {
      options += `<option value="${i}">${i}</option>`
    }
    return options;
  }

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

  /* -------------------------------------------- */
  static updateRollData(rollData) {

    let id = rollData.rollId
    let oldRollData = this.rollDataStore[id] || {}
    let newRollData = mergeObject(oldRollData, rollData)
    this.rollDataStore[id] = newRollData
  }

  /* -------------------------------------------- */
  static async onSocketMesssage(msg) {
    console.log("SOCKET MESSAGE", msg)
    if (msg.name == "msg_gm_chat_message") {
      let rollData = msg.data.rollData
      if (game.user.isGM) {
        let chatMsg = await this.createChatMessage(rollData.alias, "blindroll", {
          content: await foundry.applications.handlebars.renderTemplate(msg.data.template, rollData),
          whisper: game.user.id
        })
        chatMsg.setFlag("world", "tedeum-rolldata", rollData)
      }
    }
    if (msg.name == "msg_modify_combat_action") {
      if (game.user.isGM) {
        let { combatantId, ca } = msg.data
        let combatant = game.combat.combatants.get(combatantId)
        if (combatant) {
          console.log("sock - Modify Combat Action : ", combatant.name, ca)
          await TeDeumUtility.updateCombatantActions(combatant, ca)
        }
      }
    }
    if (msg.name == "msg_apply_damage") {
      const firstGM = game.users.find(u => u.isGM && u.active)
      if (game.user === firstGM) {
        let rollData = msg.data.rollData
        let defenderActor = TeDeumUtility.getTokenActorFromId(rollData.defenderTokenId)
        if (defenderActor) {
          await defenderActor.appliquerDegats(rollData)
        } else {
          ui.notifications.error("Impossible de trouver la cible de l'attaque, aucun degats appliqué")
        }
      }
    }
  }

  /* -------------------------------------------- */
  static async searchItem(dataItem) {
    let item
    if (dataItem.pack) {
      let id = dataItem.id || dataItem._id
      let items = await this.loadCompendium(dataItem.pack, item => item.id == id)
      item = items[0] || undefined
    } else {
      item = game.items.get(dataItem.id)
    }
    return item
  }

  /* -------------------------------------------- */
  static chatDataSetup(content, modeOverride, forceWhisper, isRoll = false) {
    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 getImpactMax(impactLevel) {
    return __maxImpacts[impactLevel]
  }
  static getNextImpactLevel(impactLevel) {
    return __nextImpacts[impactLevel]
  }
  /* -------------------------------------------- */
  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
            whisper = this.getUsers(user => user.isGM);
            blind = true;
            break
          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 async computeResults(rollData) {
    rollData.isSuccess = false
    rollData.isReussiteCritique = false
    rollData.isEchecCritique = false
    if (!rollData.difficulty || rollData.difficulty == "-") {
      return
    }
    rollData.margin = rollData.total - rollData.difficulty
    if (rollData.total >= rollData.difficulty) {
      rollData.isSuccess = true
      if (rollData.total >= 2 * rollData.difficulty) {
        rollData.isReussiteCritique = true
      }
    }
    if (rollData.diceSum == 1) {
      let critiqueRoll = await new Roll(rollData.carac.negativeDice)
      rollData.isSuccess = false
      await critiqueRoll.evaluate()
      await this.showDiceSoNice(critiqueRoll, game.settings.get("core", "rollMode"))
      rollData.critiqueRoll = foundry.utils.duplicate(critiqueRoll)
      rollData.critiqueTotal = critiqueRoll.total
      if (critiqueRoll.total > rollData.competence.system.score) {
        rollData.isEchecCritique = true
      }
    }
  }

  /* -------------------------------------------- */
  static modifyDice(dice, bonusMalus) {
    let newIndex = game.system.tedeum.config.diceValeur.indexOf(dice) + Number(bonusMalus)
    if (newIndex < 0) {
      ui.notifications.error("Vos blessures ou maladies vous empêchent de réaliser cette action, vous êtes trop faibles")
      return undefined
    }
    newIndex = Math.min(Math.max(newIndex, 0), game.system.tedeum.config.diceValeur.length - 1)
    return game.system.tedeum.config.diceValeur[newIndex]
  }

  /* -------------------------------------------- */
  static computeRollFormula(rollData, actor, isConfrontation = false) {
    let diceFormula = ""
    if (rollData.competence) {
      let localModifier = 0
      if (rollData.isViser) {
        localModifier += 1
      }
      if (rollData.isMouvement) {
        localModifier -= 1
      }
      if (rollData.arme && rollData.allongeId) {
        localModifier += rollData.allonges[rollData.allongeId].malus
        rollData.allongeMalus = rollData.allonges[rollData.allongeId].malus
        rollData.nbEsquives = rollData.allonges[rollData.allongeId]?.esquive || 0
      }
      if (rollData.attaqueCiblee && rollData.attaqueCiblee != "aucune") {
        localModifier -= 1
        rollData.loc = foundry.utils.duplicate(game.system.tedeum.config.LOCALISATION[rollData.attaqueCiblee])
      }
      let diceBase = this.modifyDice(rollData.carac.dice, localModifier + Number(rollData.bonusMalus) + rollData.santeModifier)
      if (!diceBase) return;
      diceFormula = diceBase + "x + " + rollData.compScore
    }
    if (rollData.enableProvidence) {
      diceFormula += " + " + rollData.providence.dice
    }
    return diceFormula
  }

  /* -------------------------------------------- */
  static async getLocalisation(rollData) {
    let locRoll
    if (rollData.loc) {
      locRoll = await new Roll(String(rollData.loc.score.min)).roll()
    } else {
      locRoll = await new Roll("1d20").roll()
      await this.showDiceSoNice(locRoll, game.settings.get("core", "rollMode"))
      for (let key in game.system.tedeum.config.LOCALISATION) {
        let loc = game.system.tedeum.config.LOCALISATION[key]
        if (locRoll.total >= loc.score.min && locRoll.total <= loc.score.max) {
          rollData.loc = foundry.utils.duplicate(loc)
          break
        }
      }
    }
    rollData.locRoll = foundry.utils.duplicate(locRoll)
  }

  /* -------------------------------------------- */
  static async processAttaqueMelee(rollData) {
    await this.getLocalisation(rollData)
    let actor = game.actors.get(rollData.actorId)
    let bDegats = actor.getAttaqueBonusDegats(rollData)
    rollData.degatsFormula = rollData.arme.system.degats + "+" + bDegats
    let degatsRoll = await new Roll(rollData.degatsFormula).roll()
    await this.showDiceSoNice(degatsRoll, game.settings.get("core", "rollMode"))
    rollData.degatsRoll = foundry.utils.duplicate(degatsRoll)
    rollData.degats = degatsRoll.total
  }

  /* -------------------------------------------- */
  static async processAttaqueDistance(rollData) {
    if (rollData.arme?.system.typeArme != "tir") {
      return
    }
    if (rollData.isSuccess) {
      // Roll the location
      await this.getLocalisation(rollData)
      // Now the degats
      let degatsRoll = await new Roll(rollData.arme.system.degats).roll()
      await this.showDiceSoNice(degatsRoll, game.settings.get("core", "rollMode"))
      rollData.degatsRoll = foundry.utils.duplicate(degatsRoll)
      rollData.degats = degatsRoll.total
    }
  }

  /* -------------------------------------------- */
  static async updateCombatantActions(combatant, ca) {
    await combatant.setFlag("world", "available-actions", ca)
    await combatant.update({ name: `${combatant.token.name} (${ca.nbActions} / ${ca.nbActionsMainGauche})` })
  }

  /* -------------------------------------------- */
  static async manageCombatActions(actor, rollData) {
    let combat = game.combats.active
    if (!combat) return;
    let combatant = combat.getCombatantByActor(actor)
    if (!combatant) return;
    let ca = combatant.getFlag("world", "available-actions")
    if (!ca) return;
    if (rollData.mode == "arme" && rollData.isMainGauche) {
      if (ca.nbActionsMainGauche > 0) {
        ca.nbActionsMainGauche -= 1
        ca.nbActions = Math.max(ca.nbActions - 1, 0)
      } else {
        ui.notifications.error(`${actor.name} n'a plus d'actions disponibles à la main gauche pour ce round`)
      }
    }
    if (ca.nbActions > 0) {
      ca.nbActions -= 1
    } else {
      ui.notifications.error(`${actor.name} n'a plus d'actions disponibles pour ce round`)
    }
    console.log("Manage combat actions 1", actor.name, combatant)
    if (game.user.isGM) {
      await this.updateCombatantActions(combatant, ca)
    } else {
      // Send a socket message
      game.socket.emit("system.fvtt-te-deum", { name: "msg_modify_combat_action", data: { combatantId: combatant.id, ca } });
    }
    rollData.hasActions = true
    rollData.remainingActions = ca.nbActions
    rollData.remainingActionsMainGauche = ca.nbActionsMainGauche
  }

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

    let actor = game.actors.get(rollData.actorId)
    // Fix difficulty
    if (!rollData.difficulty || rollData.difficulty == "-") {
      rollData.difficulty = "pardefaut"
    }
    rollData.difficulty = game.system.tedeum.config.difficulte[rollData.difficulty].value

    // Compute the real competence score
    if (rollData.competence) {
      if (rollData.isMainGauche) {
        rollData.competence = actor.getMeilleureCompetenceMainGauche(rollData.competence)
      }
      if (rollData.competence.system.isBase) {
        rollData.compScore = actor.system.caracteristiques[rollData.competence.system.caracteristique].value
      } else {
        rollData.compScore = rollData.competence.system.score
      }
    }
    let diceFormula = this.computeRollFormula(rollData, actor)
    if (!diceFormula) return;
    console.log("RollData", rollData, diceFormula)

    // Performs roll
    let myRoll = await new Roll(diceFormula).roll()
    await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
    rollData.roll = foundry.utils.duplicate(myRoll)
    rollData.total = myRoll.total
    rollData.diceSum = myRoll.terms[0].total
    rollData.diceFormula = diceFormula

    await this.computeResults(rollData)

    await this.processAttaqueDistance(rollData)

    await this.manageCombatActions(actor, rollData)

    let msg = await this.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-te-deum/templates/chat/chat-generic-result.hbs`, rollData)
    })
    await msg.setFlag("world", "te-deum-rolldata", rollData)
    console.log("Rolldata result", rollData)

    // Decrement providence if needed
    if (rollData.enableProvidence) {
      actor.modifyProvidence(-1)
    }
  }

  /* -------------------------------------------- */
  static sortArrayObjectsByName(myArray) {
    myArray.sort((a, b) => {
      let fa = a.name.toLowerCase();
      let fb = b.name.toLowerCase();
      if (fa < fb) {
        return -1;
      }
      if (fa > fb) {
        return 1;
      }
      return 0;
    })
  }

  /* -------------------------------------------- */
  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 "useronly": return this.getWhisperRecipientsOnly(name);
      case "selfroll": return [game.user.id];
    }
    return undefined;
  }
  /* -------------------------------------------- */
  static getWhisperRecipientsOnly(name) {
    let recep1 = ChatMessage.getWhisperRecipients(name) || [];
    return recep1
  }
  /* -------------------------------------------- */
  static getWhisperRecipientsAndGMs(name) {
    let recep1 = ChatMessage.getWhisperRecipients(name) || [];
    return recep1.concat(ChatMessage.getWhisperRecipients('GM'));
  }

  /* -------------------------------------------- */
  static blindMessageToGM(chatData) {
    chatData.whisper = this.getUsers(user => user.isGM);
    console.log("blindMessageToGM", chatData);
    game.socket.emit("system.fvtt-te-deum", { name: "msg_gm_chat_message", data: chatData });
  }


  /* -------------------------------------------- */
  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) {
    switch (rollMode) {
      case "blindroll": // GM only
        if (!game.user.isGM) {
          chatOptions.whisper = [game.user.id];
        } else {
          chatOptions.whisper = this.getUsers(user => user.isGM);
        }
        break;
      default:
        chatOptions.whisper = this.getWhisperRecipients(rollMode, name);
        break;
    }
    chatOptions.alias = chatOptions.alias || name;
    return await ChatMessage.create(chatOptions);
  }

  /* -------------------------------------------- */
  static getBasicRollData() {
    let rollData = {
      rollId: foundry.utils.randomID(16),
      type: "roll-data",
      rollMode: game.settings.get("core", "rollMode"),
      difficulty: "pardefaut",
      bonusMalus: "0",
      isReroll: false,
      enableProvidence: false,
      malusBlessures: 0,
      config: foundry.utils.duplicate(game.system.tedeum.config)
    }
    TeDeumUtility.updateWithTarget(rollData)
    return rollData
  }

  /* -------------------------------------------- */
  static updateWithTarget(rollData) {
    let target = TeDeumUtility.getTarget()
    if (target) {
      rollData.defenderTokenId = target.id
    }
  }

  /* -------------------------------------------- */
  static async createChatWithRollMode(name, chatOptions) {
    return await this.createChatMessage(name, game.settings.get("core", "rollMode"), chatOptions)
  }

  /* -------------------------------------------- */
  static async confirmDelete(actorSheet, li) {
    let itemId = li.dataset ? li.dataset.itemId : li.data("item-id");
    let msgTxt = "<p>Etes vous certain de supprimer cet item ?";
    let buttons = {
      delete: {
        icon: '<i class="fas fa-check"></i>',
        label: "Oui, aucun souci",
        callback: () => {
          actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
          if (li.slideUp) {
            li.slideUp(200, () => actorSheet.render(false));
          } else {
            li.style.display = "none";
            actorSheet.render(false);
          }
        }
      },
      cancel: {
        icon: '<i class="fas fa-times"></i>',
        label: "Annuler"
      }
    }
    msgTxt += "</p>";
    let d = new Dialog({
      title: "Confimer la suppression",
      content: msgTxt,
      buttons: buttons,
      default: "cancel"
    });
    d.render(true);
  }

}