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

/* -------------------------------------------- */
const ECRYME_WELCOME_MESSAGE_URL = "https://www.uberwald.me/gitea/public/fvtt-ecryme/raw/branch/master/welcome-message-ecryme.html"

/* -------------------------------------------- */
// Import Modules
import { EcrymeActor } from "./actors/ecryme-actor.js";
// import { EcrymeItemSheet } from "./items/ecryme-item-sheet.js";
import {
  EcrymeEquipmentSheet,
  EcrymeWeaponSheet,
  EcrymeTraitSheet,
  EcrymeSpecializationSheet,
  EcrymeManeuverSheet
} from "./items/sheets/_module.js";
import {
  EcrymeActorSheet,
  EcrymeAnnencySheet
} from "./actors/sheets/_module.js";
import { EcrymeUtility } from "./common/ecryme-utility.js";
import { EcrymeCombat } from "./app/ecryme-combat.js";
import { EcrymeItem } from "./items/ecryme-item.js";
import { EcrymeHotbar } from "./app/ecryme-hotbar.js"
import { EcrymeCharacterSummary } from "./app/ecryme-summary-app.js"
import { ECRYME_CONFIG } from "./common/ecryme-config.js"
import * as models from "./models/_module.js"

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

/************************************************************************************/
Hooks.once("init", async function () {

  console.log(`Initializing Ecryme RPG System`);

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

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

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

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = EcrymeCombat
  CONFIG.Actor.documentClass = EcrymeActor
  CONFIG.Actor.dataModels = {
    pc: models.EcrymePCDataModel,
    npc: models.EcrymeNPCDataModel,
    annency: models.EcrymeAnnencyDataModel
  }

  CONFIG.Item.documentClass = EcrymeItem
  CONFIG.Item.dataModels = {
    equipment: models.EcrymeEquipmentDataModel,
    weapon: models.EcrymeWeaponDataModel,
    trait: models.EcrymeTraitDataModel,
    specialization: models.EcrymeSpecializationDataModel,
    maneuver: models.EcrymeManeuverDataModel
  }

  game.ecryme = {
    config: ECRYME_CONFIG,
    models,
    EcrymeHotbar
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  foundry.documents.collections.Actors.registerSheet("fvtt-ecryme", EcrymeActorSheet, { types: ["pc"], makeDefault: true });
  foundry.documents.collections.Actors.registerSheet("fvtt-ecryme", EcrymeActorSheet, { types: ["npc"], makeDefault: true });
  foundry.documents.collections.Actors.registerSheet("fvtt-ecryme", EcrymeAnnencySheet, { types: ["annency"], makeDefault: true });

  foundry.documents.collections.Items.registerSheet("fvtt-ecryme", EcrymeEquipmentSheet, { types: ["equipment"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-ecryme", EcrymeWeaponSheet, { types: ["weapon"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-ecryme", EcrymeTraitSheet, { types: ["trait"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-ecryme", EcrymeSpecializationSheet, { types: ["specialization"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-ecryme", EcrymeManeuverSheet, { types: ["maneuver"], makeDefault: true });

  EcrymeUtility.init()

});

/* -------------------------------------------- */
function welcomeMessage() {
  if (game.user.isGM) {
    // Try to fetch the welcome message from the github repo "welcome-message-ecryme.html"
    fetch(ECRYME_WELCOME_MESSAGE_URL)
      .then(response => response.text())
      .then(html => {
        //console.log("Fetched welcome message:", html);
        ChatMessage.create({
          user: game.user.id,
          whisper: [game.user.id],
          content: html
        });
      })
      .catch(error => {
        console.error("Error fetching welcome message:", error);
        ChatMessage.create({
          user: game.user.id,
          whisper: [game.user.id],
          content: "<b>Bienvenue dans Ecryme RPG !</b><br>Visitez le site officiel pour plus d'informations."
        });
      });
  }
}

/* -------------------------------------------- */
async function importDefaultScene() {
  let exists = game.scenes.find(j => j.name == "Landing page 1");
  if (!exists) {
    const scenes = await EcrymeUtility.loadCompendium("fvtt-ecryme.scenes")
    let newDocuments = scenes.filter(i => i.name == "Landing page 1");
    await game.scenes.documentClass.create(newDocuments);
    game.scenes.find(i => i.name == "Landing page 1").activate();
  }

}

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

  // User warning
  if (!game.user.isGM && game.user.character == undefined) {
    ui.notifications.info("Attention ! Aucun personnage relié au joueur !");
    ChatMessage.create({
      content: "<b>WARNING</b> Le joueur  " + game.user.name + " n'est pas relié à un 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.")
  )

  welcomeMessage();
  EcrymeUtility.ready();
  EcrymeCharacterSummary.ready();
  importDefaultScene();

})

/* -------------------------------------------- */
Hooks.once("babele.init", (babele) => {
  console.log("Initializing Babele translations")
  babele.setSystemTranslationsDir("translated");
});

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