/**
 * MournbladeCYD2 system
 * Author: Uberwald
 * Software License: Prop
 */

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

/* -------------------------------------------- */
// Import Modules
import { MournbladeCYD2Actor } from "./mournblade-cyd2-actor.js";
import { MournbladeCYD2ItemSheet } from "./mournblade-cyd2-item-sheet.js";
import { MournbladeCYD2ActorSheet } from "./mournblade-cyd2-actor-sheet.js";
import { MournbladeCYD2CreatureSheet } from "./mournblade-cyd2-creature-sheet.js";
import { MournbladeCYD2CelluleSheet } from "./mournblade-cyd2-cellule-sheet.js";
import { MournbladeCYD2Utility } from "./mournblade-cyd2-utility.js";
import { MournbladeCYD2Combat } from "./mournblade-cyd2-combat.js";
import { MournbladeCYD2Item } from "./mournblade-cyd2-item.js";
import { MournbladeCYD2Automation } from "./mournblade-cyd2-automation.js";
import { MournbladeCYD2TokenHud } from "./mournblade-cyd2-hud.js";
import { MOURNBLADECYD2_CONFIG } from "./mournblade-cyd2-config.js";

/* -------------------------------------------- */
/*  Foundry VTT Initialization                  */
/* -------------------------------------------- */

/************************************************************************************/
Hooks.once("init", async function () {
  console.log(`Initializing MournbladeCYD2 RPG`);

  /* -------------------------------------------- */
  // preload handlebars templates
  MournbladeCYD2Utility.preloadHandlebarsTemplates()

  /* -------------------------------------------- */
  // Set an initiative formula for the system
  CONFIG.Combat.initiative = {
    formula: "1d10",
    decimals: 1
  };

  /* -------------------------------------------- */
  game.socket.on("system.fvtt-mournblade-cyd2", data => {
    MournbladeCYD2Utility.onSocketMesssage(data)
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = MournbladeCYD2Combat
  CONFIG.Actor.documentClass = MournbladeCYD2Actor
  CONFIG.Item.documentClass = MournbladeCYD2Item
  game.system.mournbladecyd2 = {
    MournbladeCYD2Utility,
    MournbladeCYD2Automation,
    config: MOURNBLADECYD2_CONFIG
  }

  /* -------------------------------------------- */
  // Regster sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade-cyd2", MournbladeCYD2ActorSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade-cyd2", MournbladeCYD2CreatureSheet, { types: ["creature"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade-cyd2", MournbladeCYD2CelluleSheet, { types: ["cellule"], makeDefault: true });

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd2", MournbladeCYD2ItemSheet, { makeDefault: true })

  MournbladeCYD2Utility.init()
  MournbladeCYD2Automation.init()
  MournbladeCYD2TokenHud.init()

});

/* -------------------------------------------- */
function welcomeMessage() {
  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `<div id="welcome-message-MournbladeCYD2"><span class="rdd-roll-part">
    <strong>Bienvenue dans MournbladeCYD2 et le troisième Millénaire !</strong>
    <p>Les livres de Mournblade sont nécessaires pour jouer : https://www.titam-france.fr</p>
    <p>Mournblade est un jeu de rôle publié par Titam France/Sombres projets, tous les droits leur appartiennent.</p>
    <p>Système développé par LeRatierBretonnien, support sur le <a href="https://discord.gg/pPSDNJk">Discord FR de Foundry</a>.</p>
    ` });
}

/* -------------------------------------------- */
async function importDefaultScene() {
  let exists = game.scenes.find(j => j.name == "Accueil");
  if (!exists) {
    const scenes = await MournbladeCYD2Utility.loadCompendium("fvtt-mournblade-cyd2.scenes")
    let newDocuments = scenes.filter(i => i.name == "Accueil");
    if (newDocuments) {
      await game.scenes.documentClass.create(newDocuments);
      game.scenes.find(i => i.name == "Accueil").activate();
    }
  }
}

/* -------------------------------------------- */
/*  Foundry VTT Initialization                  */
/* -------------------------------------------- */
Hooks.once("ready", function () {

  MournbladeCYD2Utility.ready()

  // User warning
  if (!game.user.isGM && game.user.character == undefined) {
    ui.notifications.info("Attention ! Aucun personnage n'est relié au joueur !");
    ChatMessage.create({
      content: "<b>ATTENTION</b> Le joueur  " + game.user.name + " n'est relié à aucun personnage !",
      user: game.user._id
    });
  }

  import("https://www.uberwald.me/fvtt_appcount/count-class-ready.js").then(moduleCounter => {
    console.log("ClassCounter loaded", moduleCounter)
    moduleCounter.ClassCounter.registerUsageCount()
  }).catch(err =>
    console.log("No stats available, giving up.")
  )

  importDefaultScene()
  welcomeMessage()

});

/* -------------------------------------------- */
/*  Foundry VTT Initialization                  */
/* -------------------------------------------- */
Hooks.on("chatMessage", (html, content, msg) => {
  if (content[0] == '/') {
    let regExp = /(\S+)/g;
    let commands = content.match(regExp);
    if (game.system.mournblade.commands.processChatCommand(commands, content, msg)) {
      return false;
    }
  }
  return true;
});
