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

/* -------------------------------------------- */
export class TeDeumUtility {

  /* -------------------------------------------- */
  static async init() {
    Hooks.on('renderChatLog', (log, html, data) => TeDeumUtility.chatListeners(html));
    //Hooks.on("getChatLogEntryContext", (html, options) => TeDeumUtility.chatMenuManager(html, options));
  }

  /* -------------------------------------------- */
  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('isGM', function () {
      return game.user.isGM
    })

    // 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} 
    }
  }

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

  /*-------------------------------------------- */
  static prepareEducationContent(formData) {
    let nbCompetences = game.system.tedeum.config.etapesEducation[formData.system.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 = game.system.tedeum.config.etapesEducation[formData.system.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 = game.system.tedeum.config.etapesEducation[formData.system.etape].hasQuestionnaire;
    formData.hasMultiplier = game.system.tedeum.config.etapesEducation[formData.system.etape].hasMultiplier;
  }

  /*-------------------------------------------- */
  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 rWinner = this.currentOpposition
      let rLooser = rollData
      if (rWinner.total < rLooser.total) {
        rWinner = rollData
        rLooser = this.currentOpposition
      }
      this.currentOpposition = undefined // Reset opposition
      let oppositionData = {
        winner: rWinner,
        looser: rLooser
      }
      let msg = await this.createChatWithRollMode(rollData.alias, {
        content: await renderTemplate(`systems/fvtt-te-deum/templates/chat/chat-opposition-result.hbs`, oppositionData)
      })
      await msg.setFlag("world", "te-deum-rolldata", rollData)
      console.log("Rolldata result", rollData)  
    }
  }

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

    html.on("click", '.chat-command-button', 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)
      }
    })
  }

  /* -------------------------------------------- */
  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'
    ]
    return 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 renderTemplate(msg.data.template, rollData),
          whisper: game.user.id
        })
        chatMsg.setFlag("world", "tedeum-rolldata", rollData)
      }
    }
  }

  /* -------------------------------------------- */
  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).roll()
      await this.showDiceSoNice(critiqueRoll, game.settings.get("core", "rollMode"))
      rollData.critiqueRoll = foundry.utils.duplicate(critiqueRoll)
      if (critiqueRoll.total > rollData.competence.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 diceBase = this.modifyDice(rollData.carac.dice, Number(rollData.bonusMalus)+rollData.santeModifier)
      if (!diceBase) return; 
      diceFormula = diceBase + "x + " + rollData.competence.system.score
    }
    if (rollData.enableProvidence) {
      diceFormula += " + " + rollData.providence.dice
    }
    return diceFormula
  }

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

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

    let msg = await this.createChatWithRollMode(rollData.alias, {
      content: await 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)
    }
    // Manage XP 
    if (rollData.isReussiteCritique || rollData.isEchecCritique) {
      actor.modifyXP(rollData.carac.key, 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.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]);
          li.slideUp(200, () => 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);
  }

}