MS_IndicatorTooltipManager = MS_IndicatorTooltipManager or {}

local MANAGER = MS_IndicatorTooltipManager

local DEFAULT_SETTINGS = {
    showName = true,
    showValue = true,
    showThresholds = false,
    showAssociatedMoodle = true,
    showMoodleTitle = true,
    showMoodleDescription = true,
    showDetailedInfo = true,
    opacity = 90,
}

local function cloneSettings(source)
    local result = {}
    for key, value in pairs(source or {}) do
        result[key] = value
    end
    return result
end

function MANAGER.getDefaultSettings()
    return cloneSettings(DEFAULT_SETTINGS)
end

function MANAGER.sanitizeOpacity(rawValue, fallback)
    local value = tonumber(rawValue)
    if value == nil then
        value = tonumber(fallback) or DEFAULT_SETTINGS.opacity
    end

    value = math.floor(value)
    if value < 0 then
        value = 0
    elseif value > 100 then
        value = 100
    end

    return value
end

local function mergeMissingTooltipSettings(settings)
    local changed = false
    if type(settings) ~= "table" then
        settings = {}
        changed = true
    end

    for key, defaultValue in pairs(DEFAULT_SETTINGS) do
        if settings[key] == nil then
            settings[key] = defaultValue
            changed = true
        end
    end

    settings.opacity = MANAGER.sanitizeOpacity(settings.opacity, DEFAULT_SETTINGS.opacity)

    return settings, changed
end

function MANAGER.getSettings(playerIndex)
    local globalConfig = MSConfig and MSConfig.getGlobalConfig and MSConfig.getGlobalConfig(playerIndex) or nil
    if not globalConfig then
        return MANAGER.getDefaultSettings()
    end

    local settings, changed = mergeMissingTooltipSettings(globalConfig.tooltipSettings)
    if changed then
        globalConfig.tooltipSettings = settings
        if MSConfig and MSConfig.updateGlobalConfig then
            MSConfig.updateGlobalConfig(playerIndex, "tooltipSettings", settings)
        end
    end

    return settings
end

function MANAGER.updateSettings(playerIndex, settings)
    local mergedSettings = mergeMissingTooltipSettings(cloneSettings(settings))
    if MSConfig and MSConfig.updateGlobalConfig then
        MSConfig.updateGlobalConfig(playerIndex, "tooltipSettings", mergedSettings)
    end
    return mergedSettings
end

function MANAGER.updateSetting(playerIndex, key, value)
    local settings = cloneSettings(MANAGER.getSettings(playerIndex))
    if key == "opacity" then
        settings.opacity = MANAGER.sanitizeOpacity(value, settings.opacity)
    else
        settings[key] = value
    end
    return MANAGER.updateSettings(playerIndex, settings)
end

function MANAGER.getOpacity(playerIndex)
    local settings = MANAGER.getSettings(playerIndex)
    return MANAGER.sanitizeOpacity(settings.opacity, DEFAULT_SETTINGS.opacity)
end

return MS_IndicatorTooltipManager
