-- Author: U_BMP
-- Group: https://vk.com/biomodprod_utilit_fs
-- Date: 06.04.2026

BMP_WardrobeClothingPack = {}
BMP_WardrobeClothingPack.MOD_DIR  = g_currentModDirectory or ""
BMP_WardrobeClothingPack.MOD_NAME = g_currentModName or "BMP_WardrobeClothingPack"
BMP_WardrobeClothingPack.PACK_XML_REL = "WardrobeClothesAddon.xml"
BMP_WardrobeClothingPack.DEBUG = true

BMP_WardrobeClothingPack._registered = false
BMP_WardrobeClothingPack._queued = false

addModEventListener(BMP_WardrobeClothingPack)

local function log(fmt, ...)
    if BMP_WardrobeClothingPack.DEBUG then
        print(string.format("[BMP_WardrobeClothingPack:%s] " .. fmt, BMP_WardrobeClothingPack.MOD_NAME, ...))
    end
end

local function getRealGlobalEnv()
    local mt = getmetatable(_G)
    if mt ~= nil and type(mt.__index) == "table" then
        return mt.__index
    end
    return _G
end

local G = getRealGlobalEnv()

local function getPendingMap()
    G.BMP_WCA_PENDING_PACKS = G.BMP_WCA_PENDING_PACKS or {}
    return G.BMP_WCA_PENDING_PACKS
end

local function getAPI()
    return G.BMP_WCA_API
end

function BMP_WardrobeClothingPack:_queuePending()
    if self._queued then
        return
    end

    local pending = getPendingMap()
    pending[self.MOD_NAME] = {
        id = self.MOD_NAME,
        modDir = self.MOD_DIR,
        xmlRel = self.PACK_XML_REL,
        opts = { debug = self.DEBUG }
    }

    self._queued = true
    log("MAIN not ready -> queued pending pack (packId=%s)", tostring(self.MOD_NAME))
end

function BMP_WardrobeClothingPack:_tryRegister()
    if self._registered then
        return
    end

    local api = getAPI()
    if api ~= nil and type(api.registerPack) == "function" then
        local ok = api.registerPack(self.MOD_NAME, self.MOD_DIR, self.PACK_XML_REL, { debug = self.DEBUG })
        if ok then
            self._registered = true
            log("Registered via GLOBAL API (packId=%s)", tostring(self.MOD_NAME))

            local pending = getPendingMap()
            pending[self.MOD_NAME] = nil
        else
            log("GLOBAL API registerPack returned false (packId=%s)", tostring(self.MOD_NAME))
        end
        return
    end

    self:_queuePending()
end

function BMP_WardrobeClothingPack:loadMap()
    self:_tryRegister()
end

function BMP_WardrobeClothingPack:update(dt)
    if not self._registered then
        self:_tryRegister()
    end
end