local addon, ns = ...
local func = ns.shared
local C = func.color
local L = ns.L

local GetNumAddOns = GetNumAddOns
local GetAddOnMemoryUsage = GetAddOnMemoryUsage
local GetAddOnInfo = GetAddOnInfo
local mem_update_interval = 10
local tooltip = nil


local mem_onclick = function(self, btn)
	local shift = IsShiftKeyDown()
	
	if btn == "RightButton" and shift then
		print(L["Collecting Garbage..."])
		collectgarbage("collect")
	elseif btn == "LeftButton" and not shift then
		if IsAddOnLoaded("Broker_EverythingConfig") then
			InterfaceOptionsFrame_OpenToCategory("Broker:Everything")
		else
			InterfaceOptionsFrame_Show()
		end
	elseif btn == "RightButton" and not shift then
		if IsAddOnLoaded("OptionHouse") then
			OptionHouse:Open(1)
		elseif IsAddOnLoaded("ACP") then
			ACP:ToggleUI()
		elseif IsAddOnLoaded("Ampere") then
			InterfaceOptionsFrame_OpenToCategory("Ampere")
		elseif IsAddOnLoaded("stAddonManager") then
			stAddonManager:LoadWindow()
		else
			print(L["No addon manager found. Tried OptionHouse, ACP, stAddonManager and Ampere."])
		end
	end
end


local function drawMemTip()
	local a = {}
	local total = 0
	local unit

	--UpdateAddOnMemoryUsage()

	for i = 1, GetNumAddOns() do
		local u = GetAddOnMemoryUsage(i)
		local n = select (1, GetAddOnInfo(i))
		total = total + u
		a[i] = {name = n, mem = floor(u * 100) / 100}
	end

	table.sort(a, function (x, y)
		return x.mem > y.mem
	end)

	local cnt = Broker_EverythingDB[L["Memory"]].mem_max_addons

	tooltip:AddHeader(C.dkyellow(L["Memory"]))

	if cnt > 0 then
		tooltip:AddLine(" ")
		tooltip:AddLine(string.format("%s %d.", L["Showing top"], Broker_EverythingDB[L["Memory"]].mem_max_addons))
		tooltip:AddLine(" ")
	else
		cnt = 1000
	end

	tooltip:AddLine(C.ltgreen(string.format("%s:", L["Addon"])), C.ltgreen(string.format("%s:", L["Memory Usage"])))
	tooltip:AddSeparator()
	for _, v in ipairs (a) do
		if v.mem > 0 then
			if v.mem > 1000 then
				v.mem = v.mem / 1000
				unit = "mb"
			else
				unit = "kb"
			end

			tooltip:AddLine(v.name, string.format("%.2f %s", v.mem, unit))
			cnt = cnt - 1

			if cnt == 0 then
				break
			end
		end
	end
	tooltip:AddSeparator()

	if total > 1000 then
		total = total / 1000
		unit = "mb"
	else
		unit = "kb"
	end

	tooltip:AddLine(string.format("%s:",L["Total Memory in use by Addons"]), string.format ("%.2f %s", total, unit))
	tooltip:AddLine(" ")

	local line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Hint: Left-click to open interface options."]),nil, nil, 2)

	if IsAddOnLoaded("OptionHouse") then
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, C.dkgreen(string.format("%s %s", L["Right-click to open"], "OptionHouse")), nil, nil, 2)
	elseif IsAddOnLoaded("ACP") then
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, C.dkgreen(string.format("%s %s", L["Right-click to open"], "Addon Control Panel")), nil, nil, 2)
	elseif IsAddOnLoaded("stAddonManager") then
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, C.dkgreen(string.format("%s %s", L["Right-click to open"], "stAddonManager")), nil, nil, 2)
	end
	line, column = tooltip:AddLine()	
	tooltip:SetCell(line, 1, C.dkgreen(L["Shift + Right-click to collect garbage."]), nil, nil, 2)
end


local mem_init = function(obj)
	if not Broker_EverythingDB[L["Memory"]].mem_max_addons then
		Broker_EverythingDB[L["Memory"]].mem_max_addons = -1
	end
	if not obj then return end

	obj = obj.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Memory"])

	obj.OnLeave = function()
		if tooltip then 
			if MouseIsOver(tooltip) then
					tooltip:SetScript('OnLeave', func.hideTooltip)
			else
					func.hideTooltip(tooltip)
			end
		end
  	end


	obj.OnEnter = function(self)
		tooltip = LibQTip:Acquire("MemTT", 2, "LEFT", "RIGHT") 
		drawMemTip()
 		func.createTooltip(self,tooltip)
	end
end

local mem_onupdate = function (self)
	local _, playerClass = UnitClass("player")
	local total = 0
	local unit = "kb"

	UpdateAddOnMemoryUsage()
	for i = 1, GetNumAddOns() do
		total = total + GetAddOnMemoryUsage(i)
	end

	if total > 1000 then
		total = total / 1000
		unit = "mb"
	end

	if Broker_EverythingDB.suffixColour == true then
		unit = C.class(unit, playerClass)
	end 
	
	self.obj.text = string.format ("%.2f", total) .. unit
end


Broker_Everything:Register(L["Memory"],
	"Interface\\Addons\\Broker_Everything\\media\\memory",--GetItemIcon(9309),
	mem_init,
	0,
	0,
	mem_onclick,
	0, --mem_tooltip,
	mem_onupdate,
	mem_update_interval)

