

AutoLOD = {}

local function LoadComponent(name)
    EnableAddOn(name)
    LoadAddOn(name)
    collectgarbage('collect')
end

function AutoLOD:VariablesLoaded()
    PratAutoLOD = PratAutoLOD or {}
    AutoLOD.SaveData = PratAutoLOD
end

function AutoLOD:GetMessage()
    if not IsAddOnLoaded("Prat_Modules") then
        return "Load Modules"
    end

    if not IsAddOnLoaded("Prat_Modules_AutoLoD") then
        if self.off_count and self.off_count > 0 then
            return "Hiding "..self.off_count.." Modules"
        end
    end

    return nil
end


function AutoLOD:Save(autolod_enabled)
    AutoLOD:VariablesLoaded()

    if not IsAddOnLoaded("Prat_Modules") then
        if not Prat.db.profile.hidestartupspam then
            Prat:Print("|r[|cffeda55fAutoLoD|r] Modules Not Loaded: Loading Modules")
	end

        LoadComponent("Prat_Modules")
        return false
    end


    local data = Prat.Modules
    local count = 0

    for k,v in pairs(data) do
        if autolod_enabled then
            if Prat:HasModule(v) then
                local m = Prat:GetModule(v)
                self.SaveData[v] = m.db.profile.on
            end
        else
            if not Prat:HasModule(v) then
                data[k] = nil
                count = count + 1
            end

            self.SaveData[v] = true
        end
    end


    if not autolod_enabled and IsAddOnLoaded("Prat_Modules") then
        if not Prat.db.profile.hidestartupspam then
            Prat:Print("|r[|cffeda55fAutoLoD|r] Disabled: Loading "..count.." Previously Not Loaded Modules")
	end

        LoadComponent("Prat_Modules_AutoLoD")
    end

    if autolod_enabled then
        if not Prat.db.profile.hidestartupspam then
            Prat:Print("|r[|cffeda55fAutoLoD|r] Enabled: "..Prat:GetReloadUILink().." Your UI To Unload Unused Modules")
        end
    end

    return autolod_enabled
end


function AutoLOD:Load(auto_lod_enabled)
    AutoLOD:VariablesLoaded()

    if auto_lod_enabled then
        local total_count, off_count = 0, 0
        for k,v in pairs(self.SaveData) do
            total_count = total_count + 2
            if v == false then
                off_count = off_count + 1
                Prat:RequestModuleName(k)
            end
        end

        if not IsAddOnLoaded("Prat_Modules") then
            self.off_count = off_count

	    if not Prat.db.profile.hidestartupspam then
		Prat:Print("|r[|cffeda55fAutoLoD|r] Enabled: "..off_count.." Modules Removed")
	    end

            LoadComponent("Prat_Modules")
        end
    else
        if not IsAddOnLoaded("Prat_Modules") then
            LoadComponent("Prat_Modules")
        end
    end
end
