/* -------------------------------------------- */
export class RFRPUtility {


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

  /* -------------------------------------------- */
  static async ready() {
    this.registerSettings();

    this.gameSystem = game.settings.get("fvtt-rolemaster-frp", "game_system");

    const skillCategories = await RFRPUtility.loadCompendium("fvtt-rolemaster-frp.skill_categories")
    this.skillCategories = skillCategories.map(i => i.toObject()).filter( i => i.system.game_system == "common" || i.system.game_system == this.gameSystem);
    // Sort skill categories by name
    this.skillCategories.sort((a, b) => a.name.localeCompare(b.name));
  }

  static getGameSystem() {
    return this.gameSystem;
  }
  
  /* -------------------------------------------- */
  static getSkillCategories() {
    return this.skillCategories
  }

  /* -------------------------------------------- */
  static registerSettings() {
    game.settings.register("fvtt-rolemaster-frp", "game_system", {
      name: "Game System",
      hint: "List of Game Systems",
      scope: "world",
      default: "rmfrp",
      requiresReload: true,
      type: String,
      config: true,
      choices: {
        rmfrp: "Rolemaster Fantasy Role Playing (RMFRP)",
        merp: "Middle Earth Role Playing (MERP)"
      }
      });

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

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

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

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

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

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

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

  /* -------------------------------------------- */
  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 loadHandlebarsTemplates() {
    const templatePaths = [
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-stats.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-fixed-info.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-armor-info.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-resistance.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-race-stat-fixed-info.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-role-traits.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-background-info.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-skill-categories.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-skills.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-fav-skills.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-items.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-weapons.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-money.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-skill-categories.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-skills.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-armor.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-herbs.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-spells.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-fav-spells.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/actors/parts/actor-fav-items.html",
      "systems/fvtt-rolemaster-frp/templates/sheets/apps/app_skill_category_importer.html"
    ];
    return loadTemplates(templatePaths);
  }

  /* -------------------------------------------- */
  static loadHandlebarsHelpers() {

    // Handlebars Helpers
    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("switch", function (value, options) {
      this.switch_value = value;
      return options.fn(this);
    });
    Handlebars.registerHelper("case", function (value, options) {
      if (value === this.switch_value) {
        return options.fn(this);
      }
    });
    // 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");
    });
  }
}