/* -------------------------------------------- */
import { DarkStarsCombat } from "./dark-stars-combat.js";
import { DarkStarsCommands } from "./dark-stars-commands.js";

/* -------------------------------------------- */
const __locationNames = { head: "Head", chest: "Chest", abdomen: "Abdomen", leftarm: "Left Arm", rightarm: "Right Arm", leftleg: "Left Leg", rightleg: "Right Leg" }
/* -------------------------------------------- */
export class DarkStarsUtility {


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

    DarkStarsCommands.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);
    })
    Handlebars.registerHelper('locationLabel', function (key) {
      return __locationNames[key]
    })


    this.gameSettings()

  }

  /*-------------------------------------------- */
  static gameSettings() {
  }

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

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

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

  }

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

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


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

    html.on("click", '.view-item-from-chat', event => {
      game.system.darkstars.creator.openItemView(event)
    })
    html.on("click", '.chat-reroll', event => {
      let messageId = this.findChatMessageId(event.currentTarget)
      let message = game.messages.get(messageId)
      let rollData = message.getFlag("world", "darkstars-roll-data")
      rollData.reroll = true
      rollData.roll = undefined
      this.rollDarkStars(rollData)
    })
  }

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

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

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

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

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

  static findChatMessage(current) {
    return DarkStarsUtility.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 DarkStarsUtility.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 async onSocketMesssage(msg) {
    console.log("SOCKET MESSAGE", msg.name)
    if (msg.name == "msg_update_roll") {
      this.updateRollData(msg.data)
    }
    if (msg.name == "msg_gm_process_attack_defense") {
      this.processSuccessResult(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)
    }
  }

  /* -------------------------------------------- */
  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 getAimingMalus(location) {
    if (location == "arm" || location == "head") {
      return -50
    }
    if (location == "torso" || location == "leg") {
      return -30
    }
    if (location == "hand") {
      return -70
    }
    return 0
  }
  /* -------------------------------------------- */
  static getAimingLocation(roll) {
    if (roll == 1) return "head"
    if (roll >= 2 && roll <= 4) return "chest"
    if (roll >= 5 && roll <= 6) return "abdomen"
    if (roll == 7) return "leftarm"
    if (roll == 8) return "rightarm"
    if (roll == 9) return "rightleg"
    if (roll == 10) return "leftleg"
    return "abdomen"
  }
  /* -------------------------------------------- */
  static locationMultiplier(location) {
    if (location == "head") return 0.3
    if (location.includes("arm")) return 0.2
    if (location.includes("leg")) return 0.4
    if (location == "chest") return 0.5
    return 0.3 // Abdomen case
  }

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

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

    // ability/save/size => 0
    rollData.percentValue = 0
    if (rollData.skill) {
      rollData.percentValue = rollData.skill.total
    }
    rollData.percentValue += rollData.bonusMalus
    rollData.diceFormula = "1d100"

    if (rollData.isAboveEffectiveRange) {
      rollData.percentValue -= 30
      rollData.percentValue = Math.max(0, rollData.percentValue)
    }

    if (rollData.mode == "weapon") {
      rollData.locationMalus = this.getAimingMalus(rollData.weaponAiming)
      rollData.percentValue += rollData.locationMalus
    }
    // Performs roll
    console.log("Roll formula", rollData.diceFormula)
    let myRoll = rollData.roll
    if (!myRoll) { // New rolls only of no rerolls
      myRoll = new Roll(rollData.diceFormula).roll({ async: false })
      await this.showDiceSoNice(myRoll, game.settings.get("core", "rollMode"))
    }
    rollData.roll = duplicate(myRoll)
    rollData.diceResult = myRoll.total
    rollData.isCriticalSuccess = rollData.diceResult <= rollData.skill.derivated.value
    rollData.isCriticalFailure = rollData.diceResult == 100
    rollData.isSuccess = rollData.diceResult == 1 || rollData.diceResult <= rollData.percentValue
    rollData.isFailure = rollData.diceResult == 100 || rollData.diceResult > rollData.percentValue
    rollData.degrees = Math.floor(rollData.percentValue / 10) - Math.floor(rollData.diceResult / 10)
    rollData.damageMultiplier = rollData.isCriticalSuccess ? 2 : 1

    if (rollData.reroll) {
      actor.modifyRerolls(-1)
      rollData.rerolls = 0 // DIsable rerolls
    }

    if (rollData.mode == "weapon") {
      if (rollData.weaponAiming == "none") {
        let rollLoc = new Roll("1d10").roll({ async: false })
        rollData.weaponAiming = this.getAimingLocation(rollLoc.total)
      }
      // Compute
      rollData.locationMultiplier = this.locationMultiplier(rollData.weaponAiming)
    }
    
    let msg = await this.createChatWithRollMode(rollData.alias, {
      content: await renderTemplate(`systems/fvtt-dark-stars/templates/chat/chat-generic-result.hbs`, rollData)
    })

    console.log("Rolldata result", rollData)
    msg.setFlag("world", "darkstars-roll-data", 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 "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-dark-stars", { 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;
    return ChatMessage.create(chatOptions);
  }

  /* -------------------------------------------- */
  static getBasicRollData() {
    let rollData = {
      rollId: randomID(16),
      rollMode: game.settings.get("core", "rollMode"),
      bonusMalus: 0,
      isAboveEffectiveRange: false,
      weaponAiming: "none"
    }
    DarkStarsUtility.updateWithTarget(rollData)
    return rollData
  }

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

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

}