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

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

/* -------------------------------------------- */
// Import Modules
import { HawkmoonActor } from "./hawkmoon-actor.js";

import { HawkmoonUtility } from "./hawkmoon-utility.js";
import { HawkmoonCombat } from "./hawkmoon-combat.js";
import { HawkmoonItem } from "./hawkmoon-item.js";
import { HawkmoonAutomation } from "./hawkmoon-automation.js";
import { HawkmoonTokenHud } from "./hawkmoon-hud.js";
import { HAWKMOON_CONFIG } from "./hawkmoon-config.js";

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

// Import AppV2 Item Sheets
import * as sheets from "./applications/sheets/_module.mjs";

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

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

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

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

  /* -------------------------------------------- */
  game.socket.on("system.fvtt-hawkmoon-cyd", data => {
    HawkmoonUtility.onSocketMesssage(data)
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = HawkmoonCombat
  CONFIG.Actor.documentClass = HawkmoonActor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    cellule: models.CelluleDataModel,
    creature: models.CreatureDataModel
  }

  CONFIG.Item.documentClass = HawkmoonItem
  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,
    artefact: models.ArtefactDataModel,
    ressource: models.RessourceDataModel,
    contact: models.ContactDataModel,
    mutation: models.MutationDataModel
  }

  CONFIG.HAWKMOON = HAWKMOON_CONFIG

  game.system.hawkmoon = {
    HawkmoonUtility,
    HawkmoonAutomation,
    config: HAWKMOON_CONFIG,
    models,
    sheets
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonPersonnageSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonCreatureSheet, { types: ["creature"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonCelluleSheet, { types: ["cellule"], makeDefault: true });

  // Register AppV2 Item Sheets
  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonTalentSheet, { types: ["talent"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonCompetenceSheet, { types: ["competence"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonArmeSheet, { types: ["arme"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonProtectionSheet, { types: ["protection"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonHistoriqueSheet, { types: ["historique"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonProfilSheet, { types: ["profil"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonEquipementSheet, { types: ["equipement"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonMonnaieSheet, { types: ["monnaie"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonArtefactSheet, { types: ["artefact"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonRessourceSheet, { types: ["ressource"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonContactSheet, { types: ["contact"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hawkmoon-cyd", sheets.HawkmoonMutationSheet, { types: ["mutation"], makeDefault: true })

  HawkmoonUtility.init()
  HawkmoonAutomation.init()
  HawkmoonTokenHud.init()

});

/* -------------------------------------------- */
function welcomeMessage() {
  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `
    <div class="hawkmoon-chat-result">
      <div class="chat-result-header">
        <img class="actor-icon" src="systems/fvtt-hawkmoon-cyd/assets/logos/hawkmoon_logo.webp" alt="Hawkmoon" />
        <div class="header-info">
          <h4 class="actor-name">Bienvenue dans Hawkmoon !</h4>
          <div class="action-title">
            <i class="fas fa-book-open"></i>
            Le Troisième Millénaire
          </div>
        </div>
      </div>

      <div class="result-details">
        <div class="details-section">
          <h5 class="section-title"><i class="fas fa-info-circle"></i> Informations importantes</h5>
          <div class="description-content">
            <p><strong>Les livres de Hawkmoon sont nécessaires pour jouer.</strong></p>
            <p>Hawkmoon est un jeu de rôle publié par <strong>Titam France / Sombres projets</strong>, tous les droits leur appartiennent.</p>
          </div>
        </div>

        <div class="details-section">
          <h5 class="section-title"><i class="fas fa-users"></i> Support & Communauté</h5>
          <div class="description-content">
            <p>Système développé par <strong>LeRatierBretonnien</strong></p>
            <p>Support disponible sur le <a href="https://discord.gg/pPSDNJk" target="_blank" style="color: #d4af37; text-decoration: underline;">Discord FR de Foundry VTT</a></p>
          </div>
        </div>
      </div>
    </div>
    `
  });
}

/* -------------------------------------------- */
async function importDefaultScene() {
  let exists = game.scenes.find(j => j.name == "Accueil");
  if (!exists) {
    const scenes = await HawkmoonUtility.loadCompendium("fvtt-hawkmoon-cyd.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 () {

  HawkmoonUtility.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.hawkmoon.commands.processChatCommand(commands, content, msg)) {
      return false;
    }
  }
  return true;
});
