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

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

/* -------------------------------------------- */
// Import Modules
import { HeritiersActor } from "./heritiers-actor.js";
import { HeritiersItem } from "./heritiers-item.js";
import { HeritiersUtility } from "./heritiers-utility.js";
import { HeritiersCombat } from "./heritiers-combat.js";
import { HERITIERS_CONFIG } from "./heritiers-config.js";

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

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

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

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

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

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

  /* -------------------------------------------- */
  game.socket.on("system.fvtt-les-heritiers", data => {
    HeritiersUtility.onSocketMesssage(data)
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = HeritiersCombat
  CONFIG.Actor.documentClass = HeritiersActor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    pnj: models.PnjDataModel
  }
  
  CONFIG.Item.documentClass = HeritiersItem
  CONFIG.Item.dataModels = {
    accessoire: models.AccessoireDataModel,
    arme: models.ArmeDataModel,
    atoutfeerique: models.AtoutFeeriqueDataModel,
    avantage: models.AvantageDataModel,
    capacitenaturelle: models.CapaciteNaturelleDataModel,
    competence: models.CompetenceDataModel,
    contact: models.ContactDataModel,
    desavantage: models.DesavantageDataModel,
    equipement: models.EquipementDataModel,
    fee: models.FeeDataModel,
    pouvoir: models.PouvoirDataModel,
    profil: models.ProfilDataModel,
    protection: models.ProtectionDataModel,
    sort: models.SortDataModel
  }
  
  // Create an object of bonus/malus from -6 to +6 signed
  HERITIERS_CONFIG.bonusMalus = Array.from({ length: 7 }, (v, k) => toString(k - 6))
  CONFIG.HERITIERS = HERITIERS_CONFIG
  
  game.system.lesheritiers = {
    HeritiersUtility,
    config: HERITIERS_CONFIG,
    models,
    sheets
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-les-heritiers", sheets.HeritiersPersonnageSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-les-heritiers", sheets.HeritiersPnjSheet, { types: ["pnj"], makeDefault: true })

  // Register AppV2 Item Sheets
  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersAccessoireSheet, { types: ["accessoire"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersArmeSheet, { types: ["arme"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersAtoutFeeriqueSheet, { types: ["atoutfeerique"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersAvantageSheet, { types: ["avantage"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersCapaciteNaturelleSheet, { types: ["capacitenaturelle"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersCompetenceSheet, { types: ["competence"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersContactSheet, { types: ["contact"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersDesavantageSheet, { types: ["desavantage"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersEquipementSheet, { types: ["equipement"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersFeeSheet, { types: ["fee"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersPouvoirSheet, { types: ["pouvoir"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersProfilSheet, { types: ["profil"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersProtectionSheet, { types: ["protection"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-les-heritiers", sheets.HeritiersSortSheet, { types: ["sort"], makeDefault: true })

  HeritiersUtility.init()

});

/* -------------------------------------------- */
async function getGuideFoundryJournalLink() {
  const isGuideFoundryJournal = name => {
    const normalizedName = name?.toLowerCase() ?? "";
    return normalizedName.includes("guide de jeu") && normalizedName.includes("foundry");
  };

  let journal = game.journal.find(j => isGuideFoundryJournal(j.name));

  if (!journal) {
    for (const pack of game.packs) {
      if (pack.documentName !== "JournalEntry") continue;
      const entry = pack.index.find(e => isGuideFoundryJournal(e.name));
      if (!entry) continue;
      journal = await pack.getDocument(entry._id ?? entry.id);
      if (journal) break;
    }
  }

  if (!journal) return "";

  return foundry.applications.ux.TextEditor.implementation.enrichHTML(
    `@UUID[${journal.uuid}]{${journal.name}}`,
    { async: true }
  );
}

/* -------------------------------------------- */
async function welcomeMessage() {
  const guideFoundryLink = await getGuideFoundryJournalLink();
  const guideFoundrySection = guideFoundryLink
    ? `
        <div class="welcome-section">
          <i class="fas fa-book"></i>
          <p>Consultez aussi le ${guideFoundryLink}.</p>
        </div>
      `
    : "";

  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `
    <div class="heritiers-chat-card heritiers-welcome-card">
      <div class="chat-card-header welcome-header">
        <div class="welcome-icon-wrapper">
          <i class="fas fa-book-open welcome-icon"></i>
        </div>
        <div class="chat-actor-info">
          <h3 class="chat-actor-name">Bienvenue dans Les Héritiers !</h3>
          <div class="chat-action-name">et la Belle Époque</div>
        </div>
      </div>
      
      <div class="chat-card-content welcome-content">
        <div class="welcome-section">
          <i class="fas fa-info-circle"></i>
          <p>Les livres du JDR <strong>Les Héritiers</strong> sont nécessaires pour jouer.</p>
        </div>
        
        <div class="welcome-section">
          <i class="fas fa-copyright"></i>
          <p><em>Les Héritiers</em> est un jeu de rôle publié par <strong>Titam France / Sombres Projets</strong>. Tous les droits leur appartiennent.</p>
        </div>
        
        <div class="welcome-section">
          <i class="fas fa-code"></i>
          <p>Système développé par <strong>LeRatierBretonnien</strong></p>
          <p>Support sur le <a href="https://discord.gg/pPSDNJk" target="_blank"><i class="fab fa-discord"></i> Discord FR de Foundry</a></p>
        </div>
        ${guideFoundrySection}
      </div>
    </div>
    ` 
  });
}

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

  HeritiersUtility.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.")
  )
  await welcomeMessage();
  importDefaultScene();

});

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