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

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

/* -------------------------------------------- */
// Import Modules
import { MournbladeActor } from "./mournblade-actor.js";
import { MournbladeItemSheet } from "./mournblade-item-sheet.js";
import { MournbladeActorSheet } from "./mournblade-actor-sheet.js";
import { MournbladeCreatureSheet } from "./mournblade-creature-sheet.js";
import { MournbladeUtility } from "./mournblade-utility.js";
import { MournbladeCombat } from "./mournblade-combat.js";
import { MournbladeItem } from "./mournblade-item.js";
import { MournbladeConfig } from "./mournblade-config.js";

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

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

  /* -------------------------------------------- */
  // preload handlebars templates
  MournbladeUtility.preloadHandlebarsTemplates();

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

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

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = MournbladeCombat
  CONFIG.Actor.documentClass = MournbladeActor
  CONFIG.Item.documentClass = MournbladeItem
  game.system.mournblade = {
    config : MournbladeConfig.getConfig(),
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade", MournbladeActorSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade", MournbladeCreatureSheet, { types: ["creature"], makeDefault: true })

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

  MournbladeUtility.init();

});

/* -------------------------------------------- */
function welcomeMessage() {
  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `<div id="welcome-message-Mournblade"><span class="rdd-roll-part">
    <strong>Bienvenue dans les Jeunes Royaumes de Mournblade !</strong>
    <p>Les livres de Mournblade sont nécessaires pour jouer : https://www.titam-france.fr</p>
    <p>Mournblade est jeu de rôle publié par Titam France/Sombres projets, tout 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 MournbladeUtility.loadCompendium("fvtt-mournblade.scenes")
    let newDocuments = scenes.filter(i => i.name == "Accueil");
    await game.scenes.documentClass.create(newDocuments);
    game.scenes.find(i => i.name == "Accueil").activate();
  }
}

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

  game.system.mournblade = {
    config : MournbladeConfig.getConfig(),
  }

  MournbladeUtility.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
    });
  }
  if (!game.user.isGM && game.user.character && !game.user.character.prototypeToken.actorLink) {
    ui.notifications.info("Le token de du joueur n'est pas connecté à l'acteur !");
    ChatMessage.create({
      content: "<b>ATTENTION</b> Le token du joueur " + game.user.name + " n'est pas connecté à l'acteur !",
      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;
});
