-- modules/LDBObjects.lua
-- Datatexts for LDB objects not already handled by other modules
local _, ns = ...
local BDT = ns.DataTexts
local L = BDT.L
local LDB = BDT.LDB

if not BDT.LDBDatatexts then BDT.LDBDatatexts = {} end

----------------------------------------------------
-- Lua Locals
----------------------------------------------------
local CreateFrame = CreateFrame
local format      = string.format

----------------------------------------------------
-- Helper Functions
----------------------------------------------------
local function ShouldSkipLDBObject(name)
    return name == "Ara Friends" -- Handled by Friends module
      or name == "Ara Guild"  -- Handled by Guild module
      or name == "CraftSimLDB" -- Only opens the CraftSim config settings
      or name == "ALL THE THINGS" -- Appears to do nothing
end

local function StripColorCodes(text)
    if not text then return nil end
    return tostring(text):gsub("|c%x%x%x%x%x%x%x%x", ""):gsub("|r", "")
end

----------------------------------------------------
-- Module wrapper for BDT
----------------------------------------------------
local function HandleLDBObject(name, obj)
    local cleanName = StripColorCodes(name)

    -- Skip objects already handled by other modules or those that are known to be "blank".
    if ShouldSkipLDBObject(cleanName) then
        return
    end

    local mod = {}

    local moduleName = "LDB: " .. cleanName
    local modulesWithLabels = {
        ["LDB: BugSack"] = true,
        ["LDB: WIM"] = true,
        ["LDB: Core Loot Manager"] = true,
    }

    ----------------------------------------------------
    -- Module Config Settings
    ----------------------------------------------------
    local function SetupModuleConfig()
        if modulesWithLabels[moduleName] then
            BDT.ModuleRegistry:AddModuleConfigSetting(moduleName, "checkbox", L["Show Label"], "showLabel", true)

            BDT.ModuleRegistry:GlobalModuleSettings(moduleName)
        else
            BDT.ModuleRegistry:GlobalModuleSettings(moduleName)
        end
    end

    SetupModuleConfig()

    function mod.Create(slotFrame)
        local f = CreateFrame("Frame", nil, slotFrame)
        f:SetAllPoints(slotFrame)

        local text = slotFrame.text
        if not text then
            text = slotFrame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
            text:SetPoint("CENTER")
            slotFrame.text = text
        end

        ----------------------------------------------------
        -- Update function
        ----------------------------------------------------
        local function Update()
            local cleanObjText = obj.text and StripColorCodes(obj.text)
            local showLabel = true
            if modulesWithLabels[moduleName] then
                showLabel = BDT:GetModuleSetting(moduleName, "showLabel", true)
            end
            local txt = ""
            if cleanName == "BugSack" then
                txt = (showLabel and cleanName .. ": " or "") .. (cleanObjText or "")
            elseif cleanName == "WIM" then
                local label = (showLabel and cleanName or "")
                local objText = (cleanObjText and ((label ~= "" and ": " or "") .. cleanObjText) or "")
                txt = label .. objText
            elseif cleanName == "Core Loot Manager" then
                local label = (showLabel and "CLM" or "")
                local objText = (cleanObjText and ((label ~= "" and ": " or "") .. cleanObjText) or "")
                txt = label .. objText
            else
                txt = cleanObjText or cleanName or L["NO TEXT"]
            end
            text:SetText(BDT.FormatUtils:ColorModuleText(moduleName, txt))
            BDT.FontManager:ApplyModuleFont(moduleName, text)
        end
        f.Update = Update
        BDT.LDBDatatexts[cleanName] = f

        ----------------------------------------------------
        -- Tooltip from LDB object
        ----------------------------------------------------
        slotFrame:EnableMouse(true)
        slotFrame:SetScript("OnEnter", function(self)
            if obj.OnTooltipShow then
                local anchor = BDT.FormatUtils:FindBestAnchorPoint(self)
                BDT.Tooltip:SetOwner(self, anchor)
                BDT.Tooltip:ClearLines()
                obj.OnTooltipShow(BDT.Tooltip)
                BDT.Tooltip:Show()
            elseif obj.OnEnter then
                obj.OnEnter(self)
            end
        end)
        slotFrame:SetScript("OnLeave", function(self)
            if obj.OnLeave then obj.OnLeave(self) end
            BDT.Tooltip:Hide()
        end)

        ----------------------------------------------------
        -- Click from LDB object
        ----------------------------------------------------
        slotFrame:RegisterForClicks("AnyUp")
        slotFrame:SetScript("OnClick", function(self, button)
            if obj.OnClick then obj.OnClick(self, button) end
        end)

        Update()

        return f
    end

    ----------------------------------------------------
    -- Register with BDT
    ----------------------------------------------------
    BDT.ModuleRegistry:RegisterDatatext("LDB: " .. cleanName, mod)

    return mod
end

for name, obj in LDB:DataObjectIterator() do
    HandleLDBObject(name, obj)
end

LDB:RegisterCallback("LibDataBroker_DataObjectCreated", function(_, name, obj)
    local cleanName = StripColorCodes(name)
    if ShouldSkipLDBObject(cleanName) then
        return
    end
    HandleLDBObject(name, obj)

    -- Mark cache as dirty and rebuild
    BDT.cache.moduleNamesDirty = true
    BDT.ModuleRegistry:CreateModuleList()
    BDT.BarManager:RebuildAllSlots()
end)

LDB:RegisterCallback("LibDataBroker_AttributeChanged", function(_, name, attr, val)
    if attr == "text" or attr == "value" then
        local cleanName = StripColorCodes(name)
        local dt = BDT.LDBDatatexts[cleanName]
        if dt and dt.Update then
            dt.Update()
        end
    end
end)
