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

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

/* -------------------------------------------- */
// Import Modules
import { WastelandActor } from "./wasteland-actor.js";
import { WastelandUtility } from "./wasteland-utility.js";
import { WastelandCombat } from "./wasteland-combat.js";
import { WastelandItem } from "./wasteland-item.js";
import { WASTELAND_CONFIG } from "./wasteland-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 Wasteland RPG`);

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

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

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

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Combat.documentClass = WastelandCombat
  CONFIG.Actor.documentClass = WastelandActor
  CONFIG.Actor.dataModels = {
    personnage: models.PersonnageDataModel,
    creature: models.CreatureDataModel
  }

  CONFIG.Item.documentClass = WastelandItem
  CONFIG.Item.dataModels = {
    arme: models.ArmeDataModel,
    artifex: models.ArtifexDataModel,
    bouclier: models.BouclierDataModel,
    capacite: models.CapaciteDataModel,
    charme: models.CharmeDataModel,
    competence: models.CompetenceDataModel,
    don: models.DonDataModel,
    equipement: models.EquipementDataModel,
    heritage: models.HeritageDataModel,
    hubris: models.HubrisDataModel,
    metier: models.MetierDataModel,
    monnaie: models.MonnaieDataModel,
    mutation: models.MutationDataModel,
    origine: models.OrigineDataModel,
    peuple: models.PeupleDataModel,
    pouvoir: models.PouvoirDataModel,
    protection: models.ProtectionDataModel
  }

  game.system.wasteland = {
    config: WASTELAND_CONFIG,
    models,
    sheets
  }

  // Initialize dynamic config options that need to be available immediately
  // Create option lists inline to ensure they're available
  const listeNiveauSkill = {}
  for (let i = 0; i <= 10; i++) {
    listeNiveauSkill[`${i}`] = `${i}`
  }
  game.system.wasteland.config.listeNiveauSkill = listeNiveauSkill
  
  const listeNiveauAttribut = {}
  for (let i = 0; i <= 10; i++) {
    listeNiveauAttribut[`${i}`] = `${i}`
  }
  game.system.wasteland.config.listeNiveauAttribut = listeNiveauAttribut

  const listeNiveauCreature = {}
  for (let i = 0; i <= 35; i++) {
    listeNiveauCreature[`${i}`] = `${i}`
  }
  game.system.wasteland.config.listeNiveauCreature = listeNiveauCreature

  const modificateurOptions = []
  for (let i = -15; i <= 15; i++) {
    modificateurOptions.push({ key: i, label: `${i >= 0 ? '+' : ''}${i}` })
  }
  game.system.wasteland.config.modificateurOptions = modificateurOptions

  const pointsAmeOptions = {}
  for (let i = 0; i <= 20; i++) {
    pointsAmeOptions[`${i}`] = `${i}`
  }
  game.system.wasteland.config.pointsAmeOptions = pointsAmeOptions

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

  // Register AppV2 Item Sheets
  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet);
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandArmeSheet, { types: ["arme"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandArtifexSheet, { types: ["artifex"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandBouclierSheet, { types: ["bouclier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandCapaciteSheet, { types: ["capacite"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandCharmeSheet, { types: ["charme"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandCompetenceSheet, { types: ["competence"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandDonSheet, { types: ["don"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandEquipementSheet, { types: ["equipement"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandHeritageSheet, { types: ["heritage"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandHubrisSheet, { types: ["hubris"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandMetierSheet, { types: ["metier"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandMonnaieSheet, { types: ["monnaie"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandMutationSheet, { types: ["mutation"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandOrigineSheet, { types: ["origine"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandPeupleSheet, { types: ["peuple"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandPouvoirSheet, { types: ["pouvoir"], makeDefault: true });
  foundry.documents.collections.Items.registerSheet("fvtt-wasteland", sheets.WastelandProtectionSheet, { types: ["protection"], makeDefault: true });

  WastelandUtility.init();

});

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


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

  WastelandUtility.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
    });
  }
  if (!game.user.isGM && game.user.character && !game.user.character.prototypeToken.actorLink) {
    ui.notifications.info("Le token de du joueur n'est pas connecté à l'acteur !");
    ChatMessage.create({
      content: "<b>ATTENTION</b> Le token du joueur " + game.user.name + " n'est pas connecté à l'acteur !",
      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();

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