/* -------------------------------------------- */
import { CrucibleCombat } from "./crucible-combat.js";
import { CrucibleCommands } from "./crucible-commands.js";

/* -------------------------------------------- */
const __level2Dice = ["d0", "d4", "d6", "d8", "d10", "d12"];
const __name2DiceValue = { "0": 0, "d0": 0, "d4": 4, "d6": 6, "d8": 8, "d10": 10, "d12": 12 }
const __skillLevel2Dice = ["0d8", "1d8", "2d8","3d8", "4d8", '6d8', "8d8", "10d8"]

/* -------------------------------------------- */
export class CrucibleUtility {


  /* -------------------------------------------- */
  static async init() {
    Hooks.on('renderChatLog', (log, html, data) => CrucibleUtility.chatListeners(html));
    Hooks.on("dropCanvasData", (canvas, data) => {
      CrucibleUtility.dropItemOnToken(canvas, data)
    });

    this.rollDataStore = {}    

    CrucibleCommands.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 getSkills() {
    return duplicate(this.skills)
  }
  /*-------------------------------------------- */
  static getWeaponSkills() {
    return duplicate(this.weaponSkills)
  }
  /*-------------------------------------------- */
  static getShieldSkills() {
    return duplicate(this.shieldSkills)
  }
  
  /* -------------------------------------------- */
  static async ready() {
    const skills = await CrucibleUtility.loadCompendium("fvtt-crucible-rpg.skills")
    this.skills = skills.map(i => i.toObject())
    this.weaponSkills = duplicate( this.skills.filter( item => item.data.isweaponskill))
    this.shieldSkills = duplicate( this.skills.filter( item => item.data.isshieldskill))
  }

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

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

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

    html.on("click", '.view-item-from-chat', event => {
      game.system.crucible.creator.openItemView(event)
    })
  }

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

    const templatePaths = [
      'systems/fvtt-crucible-rpg/templates/editor-notes-gm.html',
      'systems/fvtt-crucible-rpg/templates/partial-roll-select.html',
      'systems/fvtt-crucible-rpg/templates/partial-actor-ability-block.html',
      'systems/fvtt-crucible-rpg/templates/partial-actor-status.html',
      'systems/fvtt-crucible-rpg/templates/partial-options-abilities.html',
      'systems/fvtt-crucible-rpg/templates/partial-item-nav.html',
      'systems/fvtt-crucible-rpg/templates/partial-item-description.html',
      'systems/fvtt-crucible-rpg/templates/partial-actor-equipment.html'
    ]
    return loadTemplates(templatePaths);
  }

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

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

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

  static findChatMessage(current) {
    return CrucibleUtility.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 CrucibleUtility.findNodeMatching(current.parentElement, predicate);
    }
    return undefined;
  }

  /* -------------------------------------------- */
  static templateData(it) {
    return CrucibleUtility.data(it)?.data ?? {}
  }

  /* -------------------------------------------- */
  static data(it) {
    if (it instanceof Actor || it instanceof Item || it instanceof Combatant) {
      return it.data;
    }
    return it;
  }

  /* -------------------------------------------- */
  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 && game.user.targets.size == 1) {
      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 saveRollData(rollData) {
    game.socket.emit("system.crucible-rpg", {
      name: "msg_update_roll", data: rollData
    }); // Notify all other clients of the roll    
    this.updateRollData(rollData)
  }

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

  /* -------------------------------------------- */
  static async onSocketMesssage(msg) {
    console.log("SOCKET MESSAGE", msg.name)
    if (msg.name == "msg_update_defense_state") {
      this.updateDefenseState(msg.data.defenderId, msg.data.rollId)
    }
    if (msg.name == "msg_update_roll") {
      this.updateRollData(msg.data)
    }
    if (msg.name == "msg_gm_item_drop" && game.user.isGM) {
      let actor = game.actors.get(msg.data.actorId)
      let item
      if (msg.data.isPack) {
        item = await fromUuid("Compendium." + msg.data.isPack + "." + msg.data.itemId)
      } else {
        item = game.items.get(msg.data.itemId)
      }
      this.addItemDropToActor(actor, item)
    }
    if (msg.name == "msg_reroll_hero") {
      this.rerollHeroRemaining(msg.data.userId, msg.data.rollId)
    }
  }

  /* -------------------------------------------- */
  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 updateSkill( skill) {
    skill.data.level = skill.data.background + skill.data.basic + skill.data.class + skill.data.explevel
    if (skill.data.level > 7) { skill.data.level = 7}
    skill.data.skilldice = __skillLevel2Dice[skill.data.level]
  }

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

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

    // ability/save => 0
    let diceFormula
    let startFormula = "0d6cs>=5"
    if ( rollData.ability) {
      startFormula = String(rollData.ability.value) + "d6cs>=5"
    }
    if ( rollData.save) {
      startFormula = String(rollData.save.value) + "d6cs>=5"
    }
    if ( rollData.shield) {
      startFormula = "1" + String(rollData.shield.data.shielddie) + "cs>=5"
    }
    diceFormula = startFormula

    // skill => 2
    // feat => 4
    // bonus => 6
    if (rollData.skill) {
      let level = rollData.skill.data.level
      if (rollData.skill.data.issl2 ) {
        rollData.hasSLBonus = true
        level += 2
        if (level > 7) { level = 7}
      }
      rollData.skill.data.skilldice = __skillLevel2Dice[level]
      diceFormula += "+" + String(rollData.skill.data.skilldice) + "cs>=5"

      if (rollData.skill.data.skilltype == "complex" && rollData.skill.data.level == 0) {
        rollData.complexSkillDisadvantage = true
        rollData.rollAdvantage = "roll-disadvantage"
      }

      if (rollData.skill.data.isfeatdie) {
        rollData.hasFeatDie = true
        diceFormula += "+ 1d10cs>=5"
      } else {
        diceFormula += `+ 0d10cs>=5`
      }
      if (rollData.skill.data.bonusdice != "none") {
        rollData.hasBonusDice = rollData.skill.data.bonusdice
        diceFormula += `+ ${rollData.hasBonusDice}cs>=5`
      } else {
        diceFormula += `+ 0d6cs>=5`
      }
    } else {  
      diceFormula += `+ 0d8cs=>5 + 0d10cs>=5 + 0d6cs>=5`
    }
    
    // advantage => 8
    let advFormula = "+ 0d8cs>=5"
    if(rollData.advantage == "advantage1") {
      advFormula = "+ 1d8cs>=5"
    }
    if(rollData.advantage == "advantage2") {
      advFormula = "+ 2d8cs>=5"
    }
    diceFormula += advFormula

    // disadvantage => 10
    let disFormula = "- 0d8cs>=5"
    if(rollData.disadvantage == "disadvantage1") {
      disFormula = "- 1d8cs>=5"
    }
    if(rollData.disadvantage == "disadvantage2") {
      disFormula = "- 2d8cs>=5"
    }
    diceFormula += disFormula

    // armor => 12
    let skillArmorPenalty = 0
    for (let armor of rollData.armors) {
      if (armor.data.equipped) {
        skillArmorPenalty += armor.data.skillpenalty
      }
    }
    if (rollData.skill && rollData.skill.data.armorpenalty && skillArmorPenalty > 0 ) {
      rollData.skillArmorPenalty = skillArmorPenalty
      diceFormula += `- ${skillArmorPenalty}d8cs>=5`
    } else {
      diceFormula += `- 0d8cs>=5`
    }

    // Performs roll
    console.log("Roll formula", diceFormula)
    let myRoll = rollData.roll
    if (!myRoll) { // New rolls only of no rerolls
      myRoll = new Roll(diceFormula).roll({ async: false })
      await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
    }
    rollData.roll = myRoll
    rollData.nbSuccess = myRoll.total
    if (rollData.rollAdvantage != "none") {
      let myRoll2 = new Roll(diceFormula).roll({ async: false })
      await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
      if (rollData.rollAdvantage == "roll-advantage") {
        if ( myRoll2.total > rollData.nbSuccess) {
          rollData.roll = myRoll2
          rollData.nbSuccess = myRoll2.total
        }
      } else {
        if ( myRoll2.total < rollData.nbSuccess) {
          rollData.roll = myRoll2
          rollData.nbSuccess = myRoll2.total
        }
      }
    }
    // Manage exp
    if (rollData.skill && rollData.skill.data.level > 0) {
      let nbSkillSuccess = rollData.roll.terms[2].total
      if ( nbSkillSuccess == 0 || nbSkillSuccess == rollData.skill.data.level) {
        actor.incrementSkillExp(rollData.skill._id, 1)
      }
    }

    this.createChatWithRollMode(rollData.alias, {
      content: await renderTemplate(`systems/fvtt-crucible-rpg/templates/chat-generic-result.html`, rollData)
    })
    console.log("Rolldata result", rollData)

    // And save the roll
    this.saveRollData(rollData)
    actor.lastRoll = 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.data._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 = 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-crucible-rgp", { 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 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;
    ChatMessage.create(chatOptions);
  }

  /* -------------------------------------------- */
  static getBasicRollData() {
    let rollData = {
      rollId: randomID(16),
      rollMode: game.settings.get("core", "rollMode"),
      advantage: "none"
    }
    CrucibleUtility.updateWithTarget(rollData)
    return rollData
  }

  /* -------------------------------------------- */
  static updateWithTarget(rollData) {
    let objectDefender
    let target = CrucibleUtility.getTarget();
    if (target) {
      let defenderActor = game.actors.get(target.data.actorId)
      objectDefender = CrucibleUtility.data(defenderActor)
      objectDefender = mergeObject(objectDefender, target.data.actorData)
      rollData.defender = objectDefender
      rollData.attackerId = this.id
      rollData.defenderId = objectDefender._id
      defenderActor.addHindrancesList(rollData.effectsList)
    }
  }

  /* -------------------------------------------- */
  static createChatWithRollMode(name, chatOptions) {
    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);
  }

}