---@diagnostic disable: undefined-field, undefined-global, deprecated
---@class Private
local Private = select(2, ...)

-- Mirrors Libs/AceAddon-3.0/AceAddon-3.0.lua:57-68 (already vendored/running in
-- this addon). Every OnEvent trampoline in the addon wraps its dispatch call in
-- Private.safecall so one broken handler surfaces its error via geterrorhandler()
-- (same sink as the default UI error frame / BugSack) instead of aborting the
-- whole OnEvent invocation uncontrolled. type(func) == "function" guard makes a
-- nil/missing handler (e.g. a dispatch-table miss) a silent no-op, not an error.
local function errorhandler(err)
    return geterrorhandler()(err)
end

function Private.safecall(func, ...)
    if type(func) == "function" then
        return xpcall(func, errorhandler, ...)
    end
end

-- Consolidated from PartyMode.lua/Advertisement.lua's duplicate accidental globals
function Private:HSVtoRGB(h, s, v)
    local c = v * s
    local x = c * (1 - math.abs((h / 60) % 2 - 1))
    local m = v - c
    local r, g, b = 0, 0, 0

    if h < 60 then
        r, g, b = c, x, 0
    elseif h < 120 then
        r, g, b = x, c, 0
    elseif h < 180 then
        r, g, b = 0, c, x
    elseif h < 240 then
        r, g, b = 0, x, c
    elseif h < 300 then
        r, g, b = x, 0, c
    else
        r, g, b = c, 0, x
    end

    return r + m, g + m, b + m
end

-- Iterates group units
-- Usage: <for unit in Private:IterateGroupMembers() do>
-- Taken from WeakAuras
function Private:IterateGroupMembers(reversed, forceParty)
    local unit = (not forceParty and IsInRaid()) and "raid" or "party"
    local numGroupMembers = unit == "party" and GetNumSubgroupMembers() or GetNumGroupMembers()
    local i = reversed and numGroupMembers or (unit == "party" and 0 or 1)

    return function()
        local ret

        if i == 0 and unit == "party" then
            ret = "player"
        elseif i <= numGroupMembers and i > 0 then
            ret = unit .. i
        end

        i = i + (reversed and -1 or 1)

        return ret
    end
end

-- Takes an icon ID and returns an in-line icon string
function Private:IconString(iconID)
    return CreateTextureMarkup(iconID, 64, 64, 0, 0, 5/64, 59/64, 5/64, 59/64)
end
