/**
 * 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";

// Import DataModels
import * as models from "./models/index.mjs";

// Import AppV2 Item Sheets
import * as sheets from "./applications/sheets/_module.mjs";
import { MournbladeRollDialog } from "./mournblade-roll-dialog.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", data => {
    MournbladeUtility.onSocketMesssage(data);
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = MournbladeCombat
  CONFIG.Actor.documentClass = MournbladeActor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    creature: models.CreatureDataModel,
  }

  CONFIG.Item.documentClass = MournbladeItem
  CONFIG.Item.dataModels = {
    arme: models.ArmeDataModel,
    bouclier: models.BouclierDataModel,
    capacite: models.CapaciteDataModel,
    competence: models.CompetenceDataModel,
    don: models.DonDataModel,
    equipement: models.EquipementDataModel,
    heritage: models.HeritageDataModel,
    metier: models.MetierDataModel,
    modifier: models.ModifierDataModel,
    monnaie: models.MonnaieDataModel,
    origine: models.OrigineDataModel,
    pacte: models.PacteDataModel,
    protection: models.ProtectionDataModel,
    rune: models.RuneDataModel,
    runeeffect: models.RuneEffectDataModel,
    potion: models.PotionDataModel,
    tendance: models.TendanceDataModel,
    traitchaotique: models.TraitChaotiqueDataModel,
    traitespece: models.TraitEspeceDataModel
  }

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

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

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeArmeSheet, { types: ["arme"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeBouclierSheet, { types: ["bouclier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeCapaciteSheet, { types: ["capacite"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeCompetenceSheet, { types: ["competence"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeDonSheet, { types: ["don"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeEquipementSheet, { types: ["equipement"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeHeritageSheet, { types: ["heritage"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeMetierSheet, { types: ["metier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeModifierSheet, { types: ["modifier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeMonnaieSheet, { types: ["monnaie"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeOrigineSheet, { types: ["origine"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladePacteSheet, { types: ["pacte"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeProtectionSheet, { types: ["protection"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeRuneSheet, { types: ["rune"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeRuneEffectSheet, { types: ["runeeffect"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladePotionSheet, { types: ["potion"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeTendanceSheet, { types: ["tendance"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeTraitChaotiqueSheet, { types: ["traitchaotique"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade", sheets.MournbladeTraitEspeceSheet, { types: ["traitespece"], makeDefault: true });

  MournbladeUtility.init();

});

/* -------------------------------------------- */
async function welcomeMessage() {
  const templateData = {};
  const html = await foundry.applications.handlebars.renderTemplate("systems/fvtt-mournblade/templates/chat-welcome-message.hbs", templateData);
  
  await ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: html
  });
}

/* -------------------------------------------- */
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", async 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 !");
    await 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 !");
    await 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;
});
