/* -------------------------------------------- */
import { MaleficesCommands } from "./malefices-commands.js";


/* -------------------------------------------- */
export class MaleficesUtility {

  /* -------------------------------------------- */
  static async init() {
    Hooks.on('renderChatLog', (log, html, data) => MaleficesUtility.chatListeners(html));

    this.rollDataStore = {}
    this.defenderStore = {}

    MaleficesCommands.init();
  }

  /* -------------------------------------------- */
  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);
    })
    // 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");
    });


    game.settings.register("world", "character-summary-data", {
      name: "character-summary-data",
      scope: "world",
      config: false,
      default: { npcList: [], x: 200, y: 200 },
      type: Object
    })

    const tarots = await MaleficesUtility.loadCompendium("fvtt-malefices.malefices-tarots")
    this.tarots = tarots.map(i => i.toObject())

  }

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

  /*-------------------------------------------- */
  static getTarots() {
    return foundry.utils.duplicate(this.tarots)
  }
  static getTarot(tId) {
    return this.tarots.find(t => t._id == tId)
  }

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

  /* -------------------------------------------- */
  static async loadCompendium(compendium, filter = item => true) {
    let compendiumData = await MaleficesUtility.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 drawDeckCard(msgId) {
    if (game.user.isGM) {
      game.system.malefices.currentTirage.addCard(msgId)
    } else {
      game.socket.emit("system.fvtt-malefices", { name: "msg-draw-card", data: { msgId: msgId } })
    }
  }

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

    $(html).on("click", '.roll-destin', event => {
      let messageId = MaleficesUtility.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "rolldata")
      let actor = this.getActorFromRollData(rollData)
      actor.incDecDestin(-1)
      rollData.isReroll = true
      this.rollMalefices(rollData)
    })
    $(html).on("click", '.draw-tarot-card', event => {
      let messageId = MaleficesUtility.findChatMessageId(event.currentTarget)
      this.drawDeckCard(messageId)
    })

  }

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

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

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

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

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

  static findChatMessage(current) {
    return MaleficesUtility.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 MaleficesUtility.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 = foundry.utils.mergeObject(oldRollData, rollData)
    this.rollDataStore[id] = newRollData
  }

  /* -------------------------------------------- */
  static async onSocketMesssage(msg) {
    console.log("SOCKET MESSAGE", msg.name)
    if (msg.name == "msg-draw-card") {
      if (game.user.isGM && game.system.malefices.currentTirage) {
        game.system.malefices.currentTirage.addCard(msg.data.msgId)
      }
    }
  }

  /* -------------------------------------------- */
  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, 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 processSpecialCard(actor, rollData) {
    if (rollData.selectedCard.name.toLowerCase().includes("archange")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("archange"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "gmroll", {
          content: `Conséquence supplémentaire ! <br>L'Archange : ${actor.name} gagne 1 point de Spiritualité.`
        })
        actor.incDecAttr("spiritualite", 1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("vicaire")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("vicaire"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "blindroll", {
          content: `Conséquence supplémentaire ! <br>Le Vicaire : ${actor.name} vient de gagner 1 point en Pratique de la Magie Blanche (MPMB, secret).`
        })
        actor.incDecMPMB(1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("chance")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("chance"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "gmroll", {
          content: `Conséquence supplémentaire ! <br>La Chance : ${actor.name} a gagné 1 point de Destin.`
        })
        actor.incDecDestin(1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("mort")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("mort"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "gmroll", {
          content: `Conséquence supplémentaire ! <br>La Mort : ${actor.name} est pétrifié par la peur.`
        })
        actor.incDecDestin(1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("diable")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("diable"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "gmroll", {
          content: `Conséquence supplémentaire ! <br>Le Diable : ${actor.name} gagne 1 point de Rationnalité.`
        })
        actor.incDecAttr("rationnalite", 1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("lune noire")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("lune noire"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "blindroll", {
          content: `Conséquence supplémentaire ! <br>La Lune Noire : ${actor.name} vient de gagner 1 point de Fluide (secret).`
        })
        actor.incDecFluide(1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("grand livre")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("grand livre"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "blindroll", {
          content: `Conséquence supplémentaire ! <br>La Lune Noire : ${actor.name} vient de gagner 1 point de Fluide (secret).`
        })
        actor.incDecFluide(1)
      }
    }
    if (rollData.selectedCard.name.toLowerCase().includes("sorcier")) {
      let actorCard = actor.items.find(c => c.type == "tarot" && c.name.toLowerCase().includes("sorcier"))
      if (actorCard) {
        MaleficesUtility.createChatMessage(actor.name, "blindroll", {
          content: `Conséquence supplémentaire ! <br>Le Vicaire : ${actor.name} vient de gagner 1 point en Pratique de la Magie Noire (MPMN, secret).`
        })
        actor.incDecMPMN(1)
      }
    }

  }

  /* -------------------------------------------- */
  static computeResults(rollData) {
    rollData.isSuccess = false
    if (rollData.total <= rollData.target) {
      rollData.isSuccess = true
    }
    if (rollData.total == 1) {
      rollData.isSuccess = true
      rollData.isCritical = true
    }
    if (rollData.total == 20) {
      rollData.isSuccess = false
      rollData.isFumble = true
    }
    if (rollData.total <= Math.floor(rollData.target / 3)) {
      rollData.isPart = true
    }
  }
  /* -------------------------------------------- */
  static async tirageConfrontationMalefices(rollData) {
    let actor = game.actors.get(rollData.actorId)

    rollData.target = rollData.attr.value - rollData.confrontationDegre + rollData.confrontationModif

    let deck = this.getTarots()
    let index = Math.round(Math.random() * (deck.length - 1))
    let selectedCard = deck[index]
    selectedCard.system.ispositif = (Math.random() > 0.5)
    selectedCard.value = (selectedCard.system.ispositif) ? selectedCard.system.numericvalueup : selectedCard.system.numericvaluedown
    rollData.total = selectedCard.value
    rollData.selectedCard = selectedCard
    await MaleficesUtility.createChatMessage(actor.name, "gmroll", {
      content: await renderTemplate(`systems/fvtt-malefices/templates/chat/display-tarot-card.hbs`, selectedCard)
    })

    this.computeResults(rollData)

    if (rollData.isSuccess) {
      rollData.gainAttr = Math.ceil(rollData.confrontationDegre / 2) + ((rollData.isCritical) ? 1 : 0)
      actor.incDecAttr(rollData.attr.abbrev, rollData.gainAttr)
    } else {
      rollData.gainAttr = rollData.confrontationDegre
      actor.incDecAttr(rollData.attr.abbrev, -rollData.gainAttr)
    }

    await MaleficesUtility.createChatMessage(actor.name, "gmroll", {
      content: await renderTemplate(`systems/fvtt-malefices/templates/chat/chat-confrontation-result.hbs`, rollData)
    })
    this.processSpecialCard(actor, rollData)
  }
  /* -------------------------------------------- */
  static async rollMalefices(rollData) {

    let actor = game.actors.get(rollData.actorId)

    // Build the dice formula
    let diceFormula = "1d20"
    rollData.target = rollData.attr.value + rollData.bonusMalusPerso + rollData.bonusMalusSituation + rollData.bonusMalusDef + rollData.bonusMalusPortee
    if (rollData.attr.abbrev == "physique") {
      rollData.target += rollData.phyMalus
    }
    rollData.diceFormula = diceFormula

    // Performs roll
    console.log("Roll formula", diceFormula)
    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

    this.computeResults(rollData)

    let msg = await this.createChatWithRollMode(rollData.alias, {
      content: await foundry.applications.handlebars.renderTemplate(`systems/fvtt-malefices/templates/chat/chat-generic-result.hbs`, rollData)
    })
    msg.setFlag("world", "rolldata", rollData)
    if (rollData.mode == "initiative") {
      actor.setFlag("world", "initiative", myRoll.total)
    }

    console.log("Rolldata result", rollData)
  }

  /* -------------------------------------------- */
  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(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-malefices", { msg: "msg_gm_chat_message", data: chatGM });
  }


  /* -------------------------------------------- */
  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) {
          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;
    return await ChatMessage.create(chatOptions);
  }

  /* -------------------------------------------- */
  static getBasicRollData() {
    let rollData = {
      rollId: foundry.utils.randomID(16),
      bonusMalusPerso: 0,
      bonusMalusSituation: 0,
      bonusMalusDef: 0,
      bonusMalusPortee: 0,
      rollMode: game.settings.get("core", "rollMode")
    }
    MaleficesUtility.updateWithTarget(rollData)
    return rollData
  }

  /* -------------------------------------------- */
  static updateWithTarget(rollData) {
    let target = MaleficesUtility.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>Are you sure to remove this Item ?";
    let buttons = {
      delete: {
        icon: '<i class="fas fa-check"></i>',
        label: "Yes, remove it",
        callback: () => {
          actorSheet.actor.deleteEmbeddedDocuments("Item", [itemId]);
          li.slideUp(200, () => actorSheet.render(false));
        }
      },
      cancel: {
        icon: '<i class="fas fa-times"></i>',
        label: "Cancel"
      }
    }
    msgTxt += "</p>";
    let d = new Dialog({
      title: "Confirm removal",
      content: msgTxt,
      buttons: buttons,
      default: "cancel"
    });
    d.render(true);
  }

}