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

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

/* -------------------------------------------- */
// Import Modules
import { RdDActor } from "./actor.js";
import { RdDItemSheet } from "./item-sheet.js";
import { RdDActorSheet } from "./actor-sheet.js";
import { RdDActorCreatureSheet } from "./actor-creature-sheet.js";
import { RdDActorHumanoideSheet } from "./actor-humanoide-sheet.js";
import { RdDUtility } from "./rdd-utility.js";
import { RdDCalendrier } from "./rdd-calendrier.js";

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

/************************************************************************************/
const _patch_initiative = () => {
  Combat.prototype.rollInitiative = async function (
    ids,
    formula = null,
    messageOptions = {}
  ) {
    console.log(
      `${game.data.system.data.title} | Combat.rollInitiative()`,
      ids,
      formula,
      messageOptions
    );
    // Structure input data
    ids = typeof ids === "string" ? [ids] : ids;
    const currentId = this.combatant._id;
  
    // calculate initiative
    for ( let cId = 0; cId < ids.length; cId++) {
      const c = this.getCombatant( ids[cId] );
      //if (!c) return results;
      
      let armeCombat;
      for (const item of c.actor.data.items) {
        if (item.type == "arme" && item.data.equipe) {
          armeCombat = duplicate(item);
        }
      }
      
      //console.log("Combatat", c);
      let compName = ( armeCombat == undefined ) ? "Corps à corps" : armeCombat.data.competence;
      let competence = RdDUtility.findCompetence( c.actor.data.items, compName );      
      //const cf = formula || this._getInitiativeFormula(c);
      let rollFormula =  "1d6+" + competence.data.niveau + "+" + Math.ceil(c.actor.data.data.carac[competence.data.defaut_carac].value/2);
      const roll = this._getInitiativeRoll(c, rollFormula);
      //console.log("Compute init for", armeCombat, competence, rollFormula, roll.total);
      
      await this.updateEmbeddedEntity("Combatant",  { _id: c._id, initiative: roll.total });
      
      // Send a chat message
      let rollMode =
        messageOptions.rollMode || game.settings.get("core", "rollMode");
      let messageData = mergeObject(
        {
          speaker: {
            scene: canvas.scene._id,
            actor: c.actor ? c.actor._id : null,
            token: c.token._id,
            alias: c.token.name,
            sound: CONFIG.sounds.dice,
          },
          flavor: `${c.token.name} a fait son jet d'Initiative (Compétence ${competence.name})`,
        },
        messageOptions
      );
      roll.toMessage(messageData, { rollMode, create: true });
    }
    return this;
  };
}

/************************************************************************************/
Hooks.once("init", async function() {
  console.log(`Initializing Reve de Dragon System`);
  
  // preload handlebars templates
  RdDUtility.preloadHandlebarsTemplates();
  
  // Create specific settings
  game.settings.register("foundryvtt-reve-de-dragon", "configuration", {
    name: "configuration",
    scope: "world",
    config: false,
    type: Object
  });
  //game.settings.get("<systemName>","<settingName>") to retrieve it and  game.settings.set("<systemName>","<settingName>", <newValue>)
  
	/**
	 * Set an initiative formula for the system
	 * @type {String}
	 */
	CONFIG.Combat.initiative = {
	  formula: "1d20",
    decimals: 2
  };
  
  game.socket.on("system.foundryvtt-reve-de-dragon", data => {
    RdDUtility.performSocketMesssage( data );
  });

	// Define custom Entity classes
  CONFIG.Actor.entityClass = RdDActor;
  CONFIG.RDD = {} 
  CONFIG.RDD.resolutionTable = RdDUtility.buildResolutionTable();
  CONFIG.RDD.level_category  = RdDUtility.getLevelCategory();
  CONFIG.RDD.carac_array     = RdDUtility.getCaracArray();
  CONFIG.RDD.bonusmalus      = RdDUtility.getBonusMalus();
  game.data.RdDUtility = RdDUtility;
  
  // Register sheet application classes
  Actors.unregisterSheet("core", ActorSheet);
  Actors.registerSheet("foundryvtt-reve-de-dragon", RdDActorSheet, {
     types: ["personnage"],
     makeDefault: true }
  );
  Actors.registerSheet("wfrp4e", RdDActorCreatureSheet,  {
    types: ["creature"],
    makeDefault: true
  });
  Actors.registerSheet("wfrp4e", RdDActorHumanoideSheet,  {
    types: ["humanoide"],
    makeDefault: true
  });
  Items.unregisterSheet("core", ItemSheet);
  Items.registerSheet("foundryvtt-reve-de-dragon", RdDItemSheet, {makeDefault: true});

  // Patch the initiative formula
  _patch_initiative();
});

/* -------------------------------------------- */
/*  Foundry VTT Initialization                  */
/* -------------------------------------------- */
Hooks.once("ready", function() {
  ChatMessage.create( { title: "Bienvenu dans le Rêve !", content : "Bienvenu dans le Rêve des Dragons !<br> " +
    "Vous trouverez quelques infos pour démarrer dans ce document : @Compendium[foundryvtt-reve-de-dragon.rappel-des-regles.7uGrUHGdPu0EmIu2]{Documentation MJ/Joueurs}" } );
  
  /* Affiche le calendrier */
  let calendrier = new RdDCalendrier();
  let templatePath = "systems/foundryvtt-reve-de-dragon/templates/calendar-template.html";
  let templateData = {};
  /* DISABLEDrenderTemplate(templatePath, templateData).then(html => {
    calendrier.render(true);
  } ); */
});

/* -------------------------------------------- */
/*  Foundry VTT Initialization                  */
/* -------------------------------------------- */
Hooks.on("chatMessage", (html, content, msg) => {
  let regExp;
  regExp = /(\S+)/g;
  let commands = content.match(regExp);

  return RdDUtility.processChatCommand( commands, content, msg );
} );
