local f = InfoPanel_AddPlugin();
local UPDATE_INTERVAL = 1;
local info = {};
local nextUpdate = 0;
local NUM_ADDONS_TO_DISPLAY = 50;
local UPDATE_DELAY = 1;
local topAddOns;

local function Stats_AddCPULine(name, secs)
	if secs > 3600 then
		GameTooltip:AddDoubleLine(name, format("%.2f h", secs/3600), 1, 1, 1, 1, 0.2, 0.2);
	elseif secs > 60 then
		GameTooltip:AddDoubleLine(name, format("%.2f m", secs/60), 1, 1, 1, 1, 1, 0.2);
	elseif secs >= 1 then
		GameTooltip:AddDoubleLine(name, format("%.1f s", secs), 1, 1, 1, 0.2, 1, 0.2);
	elseif secs > 0 then
		GameTooltip:AddDoubleLine(name, format("%.1f ms", secs * 1000), 1, 1, 1, 0.2, 1, 0.2);
	end
end

local function Stats_AddMemoryLine(name, size)
	if(size > 1000) then
		GameTooltip:AddDoubleLine(name, format("%.2f mb", size/1000), 1, 1, 1, 1, 1, 0.2);
	elseif(size > 0) then
		GameTooltip:AddDoubleLine(name, format("%.2f kb", size), 1, 1, 1, 0.2, 1, 0.2);
	end
end

local function Stats_UpdateAddonsList(self, watchingCPU)
	if(watchingCPU) then
		UpdateAddOnCPUUsage();
	else
		UpdateAddOnMemoryUsage();
	end

	local total = 0
	for i=1, GetNumAddOns() do
		local value = (watchingCPU and (GetAddOnCPUUsage(i)/1000)) or GetAddOnMemoryUsage(i);
		local name = GetAddOnInfo(i);
		total = total + value;

		for j,addon in ipairs(topAddOns) do
			if(value > addon.value) then
				for k = NUM_ADDONS_TO_DISPLAY, 1, -1 do
					if(k == j) then
						topAddOns[k].value = value;
						topAddOns[k].name = GetAddOnInfo(i);
						break
					elseif(k ~= 1) then
						topAddOns[k].value = topAddOns[k-1].value;
						topAddOns[k].name = topAddOns[k-1].name;
					end
				end
				break
			end
		end
	end

	if (total > 0) then
		if(watchingCPU) then
			GameTooltip:SetText("애드온 CPU 사용량");
		else
			GameTooltip:SetText("애드온 메모리 사용량");
		end
		GameTooltip:AddLine("-------------------------------------------------------------");

		for _,addon in ipairs(topAddOns) do
			if(watchingCPU) then
				Stats_AddCPULine(addon.name, addon.value);
			else
				Stats_AddMemoryLine(addon.name, addon.value);
			end
		end

		GameTooltip:AddLine("-------------------------------------------------------------");
		if(watchingCPU) then
			Stats_AddCPULine("합계", total);
		else
			Stats_AddMemoryLine("합계", total);
		end
	end
	GameTooltip:AddLine("-------------------------------------------------------------");
	GameTooltip:AddLine("ALT-LeftClick : 누수 메모리 정리, ALT-RightClick : 애드온 재시작");
	GameTooltip:AddLine("Shift-LeftClick : 접속 종료, Shift-RightClick : 게임 종료");
	GameTooltip:Show();
end

local function Stats_UpdateTooltip(self)
	if GetNumAddOns() < NUM_ADDONS_TO_DISPLAY then
		NUM_ADDONS_TO_DISPLAY = GetNumAddOns();
	end
	--clear topAddOns list
	if topAddOns then
		for i,addon in pairs(topAddOns) do
			addon.value = 0;
		end
	else
		topAddOns = {};
		for i=1, NUM_ADDONS_TO_DISPLAY do
			topAddOns[i] = {name = "", value = 0};
		end
	end

	Stats_UpdateAddonsList(self, GetCVar("scriptProfile") == "1" and not IsModifierKeyDown());
end

-- Perform a GC
local function PerformGC()
	UpdateAddOnMemoryUsage();
	local memBefore = gcinfo();
	collectgarbage();
	UpdateAddOnMemoryUsage();
	local memAfter = gcinfo();
	AzMsg(("|2메모리 정리|r 수행전: |1%d|r kb, 수행후: |1%d|r kb, 감소: |1%d|r kb."):format(memBefore,memAfter,memBefore-memAfter));
end

local function Stats_OnClick(self, button)
	if IsAltKeyDown() and button == "RightButton" then 
		ReloadUI();
		return; 
	elseif IsAltKeyDown() and button == "LeftButton" then
		PerformGC();
		return;
	end
	if (IsShiftKeyDown() and button == "RightButton") then
		ForceQuit();
	elseif (IsShiftKeyDown() and button == "LeftButton") then
		Logout();
	end
end
--------------------------------------------------------------------------------------------------------
--                                             Perform Bar                                            --
--------------------------------------------------------------------------------------------------------

-- OnUpdate
local function OnUpdate(self,elapsed)
	nextUpdate = (nextUpdate - elapsed);
	if (nextUpdate <= 0) then
		info.fps = GetFramerate();
		info.down, info.up, info.latency = GetNetStats();
		info.mem = gcinfo();

		InfoPanel_SetText(f,"|cff00ff00%.1ffps  |cffffd100%dms|r  %.2fMb",info.fps,info.latency,info.mem / 1024);
		nextUpdate = UPDATE_INTERVAL;
	end
end

-- Mouse OnEnter
local function OnEnter(self)
	if self:GetRight() >= (GetScreenWidth() / 2) then
		GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT")
	else
		GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
	end
  Stats_UpdateTooltip(self);
--[[
	InfoPanel_MakeTip(f,"Performance Info");

	GameTooltip:AddDoubleLine("Frame Rate",format("%.2f",info.fps),nil,nil,nil,1,1,1);

	GameTooltip:AddLine(" ");
	GameTooltip:AddDoubleLine("Bandwidth Down",format("%.2f bytes/s",info.down * 1024),nil,nil,nil,1,1,1);
	GameTooltip:AddDoubleLine("Bandwidth Up",format("%.2f bytes/s",info.up * 1024),nil,nil,nil,1,1,1);
	GameTooltip:AddDoubleLine("Latency",format("%d ms",info.latency),nil,nil,nil,1,1,1);

	GameTooltip:AddLine(" ");
	GameTooltip:AddDoubleLine("Memory Usage",format("%d kb",info.mem),nil,nil,nil,1,1,1);

	local vers, build, date = GetBuildInfo();
	GameTooltip:AddLine(" ");
	GameTooltip:AddLine(format("WoW %s build %s - %s",vers,build,date),0,1,0);

	GameTooltip:Show();
]]--
end

--------------------------------------------------------------------------------------------------------
--                                              Finalize                                              --
--------------------------------------------------------------------------------------------------------

--f.icon:SetTexture("Interface\\Icons\\Ability_Hunter_Pathfinding");
f.icon:SetWidth(1);
f:SetScript("OnEnter",OnEnter);
f:SetScript("OnUpdate",OnUpdate);
f:SetScript("OnClick",Stats_OnClick);