/**
 * RdD system
 * Author: LeRatierBretonnien
 * Software License: GNU GPLv3
 */

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

/* -------------------------------------------- */
// Import Modules
import { SoSActor } from "./actor.js";
import { SoSItemSheet } from "./item-sheet.js";
import { SoSActorSheet } from "./actor-sheet.js";
import { SoSUtility } from "./sos-utility.js";
import { SoSCombat } from "./sos-combat.js";
import { gearConverter } from "./gears_convert.js";
import { SoSGMDeck } from "./sos-gm-deck.js";

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

/************************************************************************************/
Hooks.once("init", async function () {
  console.log(`Initializing Shadows Over Sol System`);

  /* -------------------------------------------- */
  game.settings.register("foundryvtt-shadows-over-sol", "gmDeck", {
    name: "gmDeck",
    scope: "world",
    config: false,
    type: Object
  });

  /* -------------------------------------------- */
  // preload handlebars templates
  SoSUtility.preloadHandlebarsTemplates();
  // Create useful storage space
  let html = await renderTemplate('systems/foundryvtt-shadows-over-sol/templates/gm-deck.html', {} );
  let gmDeck = new SoSGMDeck(html);
  game.system.sos = { 
    gmDeck: gmDeck,
  }

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

  /* -------------------------------------------- */
  game.socket.on("system.foundryvtt-shadows-over-sol", data => {
    SoSUtility.onSocketMesssage(data);
  });

  /* -------------------------------------------- */
  // Define custom Entity classes
  CONFIG.Actor.documentClass = SoSActor;
  CONFIG.Combat.documentClass = SoSCombat;
  CONFIG.SoS = {
  }

  /* -------------------------------------------- */
  // Register sheet application classes
  Actors.unregisterSheet("core", ActorSheet);
  Actors.registerSheet("foundryvtt-shadows-over-sol", SoSActorSheet, { types: ["character"], makeDefault: true });
  Items.unregisterSheet("core", ItemSheet);
  Items.registerSheet("foundryvtt-shadows-over-sol", SoSItemSheet, { makeDefault: true });

  // Init/registers
  Hooks.on('renderChatLog', (log, html, data) => {
    SoSUtility.registerChatCallbacks(html);
  });
  // Init/registers
  Hooks.on('updateCombat', (combat, round, diff, id) => {
    SoSUtility.updateCombat(combat, round, diff, id);
  });
  
});

/* -------------------------------------------- */
function welcomeMessage() {
  //ChatUtility.removeMyChatMessageContaining('<div id="welcome-message-sos">');
  ChatMessage.create({
    user: game.user.id,
    whisper: [game.user.id],
    content: `<div id="welcome-message-sos"><span class="rdd-roll-part">Welcome !</div>
    ` });
}

/* -------------------------------------------- */
// Register world usage statistics
function registerUsageCount( registerKey ) {
  if ( game.user.isGM ) {
    game.settings.register(registerKey, "world-key", {
      name: "Unique world key",
      scope: "world",
      config: false,
      default: "XXX",
      type: String
    });

    let worldKey = game.settings.get(registerKey, "world-key")
    if ( worldKey == undefined || worldKey == "" ) {
      worldKey = randomID(32)
      game.settings.set(registerKey, "world-key", worldKey )
    }
    // Simple API counter
    let regURL = `https://www.uberwald.me/fvtt_appcount/count.php?name="${registerKey}"&worldKey="${worldKey}"&version="${game.release.generation}.${game.release.build}"&system="${game.system.id}"&systemversion="${game.system.version}"`
    $.ajax(regURL)
    /* -------------------------------------------- */
  }
}

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

  // User warning
  if (!game.user.isGM && game.user.character == undefined) {
    ui.notifications.info("Warning ! You are not linked to any actor !");
    ChatMessage.create({
      content: "<b>WARNING</b> Player " + game.user.name + " is not linked to an actor !",
      user: game.user._id
    });
  }
  registerUsageCount("foundryvtt-shadows-over-sol")
  
  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);
    if ( commands[0] == '/gmdeck') {
      game.system.sos.gmDeck.render( true );
      return false;
    }
  }
  return true;
});


/* -------------------------------------------- */
Hooks.on("getCombatTrackerEntryContext", (html, options) => {
  //SoS.pushInitiativeOptions(html, options);
}
)
