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

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

/* -------------------------------------------- */
// Import Modules
import { MournbladeCYD2Actor } from "./mournblade-cyd2-actor.js";
import * as sheets from "./applications/sheets/_module.mjs";
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";
import { MournbladeCYD2Effects } from "./mournblade-cyd2-effects.js";

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

/* -------------------------------------------- */
/*  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-cyd-2-0", data => {
    MournbladeCYD2Utility.onSocketMessage(data)
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = MournbladeCYD2Combat
  CONFIG.Actor.documentClass = MournbladeCYD2Actor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    creature: models.CreatureDataModel
  }
  CONFIG.Item.documentClass = MournbladeCYD2Item
  CONFIG.Item.dataModels = {
    talent: models.TalentDataModel,
    historique: models.HistoriqueDataModel,
    profil: models.ProfilDataModel,
    competence: models.CompetenceDataModel,
    arme: models.ArmeDataModel,
    protection: models.ProtectionDataModel,
    monnaie: models.MonnaieDataModel,
    equipement: models.EquipementDataModel,
    ressource: models.RessourceDataModel,
    don: models.DonDataModel,
    pacte: models.PacteDataModel,
    rune: models.RuneDataModel,
    runeeffect: models.RuneEffectDataModel,
    tendance: models.TendanceDataModel,
    traitchaotique: models.TraitChaotiqueDataModel,
    traitespece: models.TraitEspeceDataModel,
    traitdemoniaque: models.TraitDemoniaqueDataModel,
    pouvoirselementaire: models.PouvoirElementaireDataModel,
    capaciteautomata: models.CapaciteAutomataDataModel
  }
  game.system.mournbladecyd2 = {
    MournbladeCYD2Utility,
    MournbladeCYD2Automation,
    MournbladeCYD2Effects,
    config: MOURNBLADECYD2_CONFIG
  }

  // Register sheet application classes (AppV2)
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2PersonnageSheet, { types: ["personnage"], makeDefault: true });
  foundry.documents.collections.Actors.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2CreatureSheet, { types: ["creature"], makeDefault: true });

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2CompetenceSheet, { types: ["competence"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2TalentSheet, { types: ["talent"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2HistoriqueSheet, { types: ["historique"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2ProfilSheet, { types: ["profil"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2ArmeSheet, { types: ["arme"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2ProtectionSheet, { types: ["protection"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2MonnaieSheet, { types: ["monnaie"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2EquipementSheet, { types: ["equipement"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2RessourceSheet, { types: ["ressource"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2DonSheet, { types: ["don"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2PacteSheet, { types: ["pacte"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2RuneSheet, { types: ["rune"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2RuneEffectSheet, { types: ["runeeffect"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2TendanceSheet, { types: ["tendance"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2TraitChaotiqueSheet, { types: ["traitchaotique"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2TraitEspeceSheet, { types: ["traitespece"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2TraitDemoniaqueSheet, { types: ["traitdemoniaque"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2PouvoirElementaireSheet, { types: ["pouvoirselementaire"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-mournblade-cyd-2-0", sheets.MournbladeCYD2CapaciteAutomataSheet, { types: ["capaciteautomata"], makeDefault: true });

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

});

/* -------------------------------------------- */
function welcomeMessage() {
  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `<div class="mournblade-welcome-message">
  <div class="welcome-header">
    <div class="welcome-icon"><i class="fas fa-sword"></i></div>
    <h2 class="welcome-title">Mournblade CYD 2.0</h2>
    <div class="welcome-subtitle">Système FoundryVTT — Bienvenue !</div>
  </div>
  <div class="welcome-content">
    <div class="welcome-section">
      <div class="section-icon"><i class="fas fa-book-open"></i></div>
      <div class="section-text">
        <strong>Livres nécessaires</strong>
        <p>Les livres de Mournblade sont nécessaires pour jouer. Supplément de conversion CYD 2.0 requis.</p>
        <a class="welcome-link" href="https://www.lahiette.com/leratierbretonnien/mournblade-et-le-cyd-2-0/" target="_blank"><i class="fas fa-external-link-alt"></i>Règles PAO 0.9</a>
      </div>
    </div>
    <div class="welcome-section">
      <div class="section-icon"><i class="fas fa-copyright"></i></div>
      <div class="section-text">
        <strong>Droits</strong>
        <p>Mournblade est un jeu Titam.</p>
      </div>
    </div>
    <div class="welcome-section">
      <div class="section-icon"><i class="fab fa-discord"></i></div>
      <div class="section-text">
        <strong>Support</strong>
        <p>Système développé par LeRatierBretonnien.</p>
        <a class="welcome-link" href="https://discord.gg/pPSDNJk" target="_blank"><i class="fab fa-discord"></i>Discord FR Foundry</a>
      </div>
    </div>
  </div>
  <div class="welcome-footer">
    <i class="fas fa-dice-d20"></i>
    <span>Bonne partie !</span>
  </div>
</div>`
  });
}

/* -------------------------------------------- */
async function importDefaultScene() {
  let exists = game.scenes.find(j => j.name == "Accueil");
  if (!exists) {
    const scenes = await MournbladeCYD2Utility.loadCompendium("fvtt-mournblade-cyd-2-0.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.mournbladecyd2.commands?.processChatCommand(commands, content, msg)) {
      return false;
    }
  }
  return true;
});
