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

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

/* -------------------------------------------- */
// Import Modules
import { YggdrasillActor } from "./yggdrasill-actor.js";
import { YggdrasillUtility } from "./yggdrasill-utility.js";
import { YggdrasillCombat } from "./yggdrasill-combat.js";
import { YGGDRASILL_CONFIG } from "./yggdrasill-config.js";
import { ClassCounter} from "https://www.uberwald.me/fvtt_appcount/count-class-ready.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 Yggdrasill`);

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

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

  game.system.config = YGGDRASILL_CONFIG

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

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Actor.documentClass = YggdrasillActor;
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    figurant: models.FigurantDataModel
  };

  CONFIG.Combat.documentClass = YggdrasillCombat;
  
  CONFIG.Item.dataModels = {
    competence: models.CompetenceDataModel,
    don: models.DonDataModel,
    faiblesse: models.FaiblesseDataModel,
    blessure: models.BlessureDataModel,
    maladie: models.MaladieDataModel,
    poison: models.PoisonDataModel,
    prouesse: models.ProuesseDataModel,
    sortsejdr: models.SortsejdrDataModel,
    sortgaldr: models.SortgaldrDataModel,
    rune: models.RuneDataModel,
    armecc: models.ArmeccDataModel,
    armedist: models.ArmedistDataModel,
    armure: models.ArmureDataModel,
    bouclier: models.BouclierDataModel,
    equipement: models.EquipementDataModel,
    monnaie: models.MonnaieDataModel,
    effetmagique: models.EffetmagiqueDataModel
  };

  CONFIG.Yggdrasill = {
  }
  
  game.system.yggdrasill = {
    config: YGGDRASILL_CONFIG,
    models,
    sheets
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  
  // Register AppV2 Actor Sheets
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet);
  foundry.documents.collections.Actors.registerSheet("fvtt-yggdrasill", sheets.YggdrasillPersonnageSheet, { types: ["personnage"], makeDefault: true });
  foundry.documents.collections.Actors.registerSheet("fvtt-yggdrasill", sheets.YggdrasillFigurantSheet, { types: ["figurant"], makeDefault: true });

  // Register AppV2 Item Sheets
  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillCompetenceSheet, { types: ["competence"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillDonSheet, { types: ["don"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillFaiblesseSheet, { types: ["faiblesse"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillBlessureSheet, { types: ["blessure"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillMaladieSheet, { types: ["maladie"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillPoisonSheet, { types: ["poison"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillProuesseSheet, { types: ["prouesse"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillSortsejdrSheet, { types: ["sortsejdr"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillSortgaldrSheet, { types: ["sortgaldr"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillRuneSheet, { types: ["rune"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillArmeccSheet, { types: ["armecc"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillArmedistSheet, { types: ["armedist"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillArmureSheet, { types: ["armure"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillBouclierSheet, { types: ["bouclier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillEquipementSheet, { types: ["equipement"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillMonnaieSheet, { types: ["monnaie"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-yggdrasill", sheets.YggdrasillEffetmagiqueSheet, { types: ["effetmagique"], makeDefault: true });

});

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

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

  // User warning
  if (!game.user.isGM && game.user.character == undefined) {
    ui.notifications.info("Attention ! Vous n'est connecté à aucun personnage");
    ChatMessage.create({
      content: "<b>WARNING</b> Le joueur  " + game.user.name + " n'est pas connecté à un personnage !",
      user: game.user.id
    });
  }

  ClassCounter.registerUsageCount()
  welcomeMessage()
});

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

/* -------------------------------------------- */
/*  Chat Message Rendering                      */
/* -------------------------------------------- */
Hooks.on("renderChatMessageHTML", (message, html, data) => {
  // Handle collapsible magic details
  html.querySelector('.magic-header.collapsible')?.addEventListener('click', function() {
    const header = this;
    const content = header.parentElement.querySelector('.magic-content');
    
    // Toggle collapsed state
    content?.classList.toggle('collapsed');
    header.classList.toggle('expanded');
  });
  
  // Handle collapsible weapon details
  html.querySelector('.weapon-header.collapsible')?.addEventListener('click', function() {
    const header = this;
    const content = header.parentElement.querySelector('.weapon-content');
    
    // Toggle collapsed state
    content?.classList.toggle('collapsed');
    header.classList.toggle('expanded');
  });
});
