/**
 * Cthulhu Eternal RPG System
 * Author: LeRatierBretonnien/Uberwald
 */

import { SYSTEM } from "./module/config/system.mjs"
globalThis.SYSTEM = SYSTEM // Expose the SYSTEM object to the global scope

// Import modules
import * as models from "./module/models/_module.mjs"
import * as documents from "./module/documents/_module.mjs"
import * as applications from "./module/applications/_module.mjs"

import { handleSocketEvent } from "./module/socket.mjs"
import HamalronUtils from "./module/utils.mjs"

export class ClassCounter { static printHello() { console.log("Hello") } static sendJsonPostRequest(e, s) { const t = { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify(s) }; return fetch(e, t).then((e => { if (!e.ok) throw new Error("La requête a échoué avec le statut " + e.status); return e.json() })).catch((e => { throw console.error("Erreur envoi de la requête:", e), e })) } static registerUsageCount(e = game.system.id, s = {}) { if (game.user.isGM) { game.settings.register(e, "world-key", { name: "Unique world key", scope: "world", config: !1, default: "", type: String }); let t = game.settings.get(e, "world-key"); null != t && "" != t && "NONE" != t && "none" != t.toLowerCase() || (t = foundry.utils.randomID(32), game.settings.set(e, "world-key", t)); let a = { name: e, system: game.system.id, worldKey: t, version: game.system.version, language: game.settings.get("core", "language"), remoteAddr: game.data.addresses.remote, nbInstalledModules: game.modules.size, nbActiveModules: game.modules.filter((e => e.active)).length, nbPacks: game.world.packs.size, nbUsers: game.users.size, nbScenes: game.scenes.size, nbActors: game.actors.size, nbPlaylist: game.playlists.size, nbTables: game.tables.size, nbCards: game.cards.size, optionsData: s, foundryVersion: `${game.release.generation}.${game.release.build}` }; this.sendJsonPostRequest("https://www.uberwald.me/fvtt_appcount/count_post.php", a) } } }

Hooks.once("init", function () {
  console.info("HAMALRON JDR | Initializing System")
  console.info(SYSTEM.ASCII)

  globalThis.Hamalron = game.system
  game.system.CONST = SYSTEM

  // Expose the system API
  game.system.api = {
    applications,
    models,
    documents,
    openTarotDeckManager: () => applications.HamalronTarotDeckManager.openManager(),
  }

  CONFIG.Combat.initiative = {
    formula: '1d6',
    decimals: 0
  };

  CONFIG.Actor.documentClass = documents.HamalronActor
  CONFIG.Actor.dataModels = {
    personnage: models.HamalronPersonnage,
    pnj: models.HamalronPNJ,
  }

  CONFIG.Item.documentClass = documents.HamalronItem
  CONFIG.Item.dataModels = {
    arme: models.HamalronArme,
    armure: models.HamalronArmure,
    competence: models.HamalronCompetence,
    equipement: models.HamalronEquipement,
    faction: models.HamalronFaction,
    langue: models.HamalronLangue,
    peuple: models.HamalronPeuple,
    region: models.HamalronRegion,
    sortilege: models.HamalronSortilege,
    tarot: models.HamalronTarot,
  }

  // Register sheet application classes
  foundry.documents.collections.Actors.unregisterSheet("core", foundry.appv1.sheets.ActorSheet)
  foundry.documents.collections.Actors.registerSheet("fvtt-hamalron", applications.HamalronPersonnageSheet, { types: ["personnage"], makeDefault: true })
  foundry.documents.collections.Actors.registerSheet("fvtt-hamalron", applications.HamalronEnemySheet, { types: ["pnj"], makeDefault: true })

  foundry.documents.collections.Items.unregisterSheet("core", foundry.appv1.sheets.ItemSheet)
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronArmeSheet, { types: ["arme"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronArmureSheet, { types: ["armure"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronCompetenceSheet, { types: ["competence"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronEquipementSheet, { types: ["equipement"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronFactionSheet, { types: ["faction"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronLangueSheet, { types: ["langue"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronPeupleSheet, { types: ["peuple"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronRegionSheet, { types: ["region"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronSortilegeSheet, { types: ["sortilege"], makeDefault: true })
  foundry.documents.collections.Items.registerSheet("fvtt-hamalron", applications.HamalronTarotSheet, { types: ["tarot"], makeDefault: true })

  // Other Document Configuration
  CONFIG.ChatMessage.documentClass = documents.HamalronChatMessage

  // Dice system configuration
  CONFIG.Dice.rolls.push(documents.HamalronRoll)

  game.settings.register("fvtt-hamalron", "worldKey", {
    name: "Unique world key",
    scope: "world",
    config: false,
    type: String,
    default: "",
  })

  // Activate socket handler
  game.socket.on(`system.${SYSTEM.id}`, handleSocketEvent)

  HamalronUtils.registerSettings()
  HamalronUtils.registerHandlebarsHelpers()

  console.info("FTL Nomad | System Initialized")
})


/**
 * Perform one-time configuration of system configuration objects.
 */
function preLocalizeConfig() {
  const localizeConfigObject = (obj, keys) => {
    for (let o of Object.values(obj)) {
      for (let k of keys) {
        o[k] = game.i18n.localize(o[k])
      }
    }
  }
}

Hooks.once("ready", function () {
  console.info("FTL Nomad | Ready")
  if (game.user.isGM) {
    ClassCounter.registerUsageCount("fvtt-hamalron", {})
  }
  preLocalizeConfig()

})

// Add button to scene controls for Tarot Deck Manager
Hooks.on("getSceneControlButtons", (controls) => {
  if (game.user.isGM) {
    // Handle both old and new Foundry API
    const controlsArray = Array.isArray(controls) ? controls : controls.controls || [];
    const tokenControls = controlsArray.find(c => c.name === "token")
    if (tokenControls) {
      tokenControls.tools.push({
        name: "tarot-deck",
        title: "HAMALRON.TarotDeck.Title",
        icon: "fas fa-cards",
        button: true,
        onClick: () => applications.HamalronTarotDeckManager.openManager(),
      })
    }
  }
})

Hooks.on("renderChatMessageHTML", (message, html, data) => {
})


/**
 * Create a macro when dropping an entity on the hotbar
 * Item      - open roll dialog
 * Actor     - open actor sheet
 * Journal   - open journal sheet
 */
Hooks.on("hotbarDrop", (bar, data, slot) => {
  if (["Actor", "Item", "JournalEntry", "skill", "weapon"].includes(data.type)) {
    // TODO -> Manage this
    return false
  }
})
