Quantcast
--[[-----------------------------------------------------------------------
	Broker Systatus - system info and menu access for DataBroker displays
	Copyright (c) 2016 Andrew Mordecai <armordecai@protonmail.ch>
	This code is released under the zlib/libpng license.
-------------------------------------------------------------------------]]

local ICON = "Interface\\AddOns\\Broker_Systatus\\Icon"

local Plugin = LibStub("LibDataBroker-1.1"):NewDataObject("Systatus", {
	type  = "data source",
	icon  = ICON.."Medium",
	text  = "???",
})

local function GetLatencyState(latency)
	if latency > PERFORMANCEBAR_MEDIUM_LATENCY then
		return "|cffff0000", ICON.."High"
	elseif latency > PERFORMANCEBAR_LOW_LATENCY then
		return "|cffffff00", ICON.."Medium"
	else
		return "|cff00ff00", ICON.."Low"
	end
end

--------------------------------
-- Update the icon and text periodically
--------------------------------

local function Update()
	local latency = max(GetNetStats())
	local color, icon = GetLatencyState(latency)
	Plugin.text = string.format("%s%dms", color, latency)
	Plugin.icon = icon
	C_Timer.After(5, Update)
end

C_Timer.After(5, Update)

--------------------------------
-- Update the tooltip while it's open
--------------------------------

local function UpdateTooltip(self)
	if not GameTooltip:IsOwned(self.owner) then
		return self:Hide()
	end

	GameTooltip:ClearLines()
	GameTooltip:AddLine("System Info")

	GameTooltip:AddDoubleLine("Bandwidth", string.format("|cffffffff%s|r Mbps", GetAvailableBandwidth()))

	local dl = floor(GetDownloadedPercentage() * 100 + 0.5)
	if dl > 0 and dl < 100 then
		GameTooltip:AddDoubleLine("Download", string.format("|cffffffff%d|r%%", dl))
	end

	GameTooltip:AddDoubleLine("Framerate", string.format("|cffffffff%d|r FPS", GetFramerate()))

	local _, _, home, world = GetNetStats()
	GameTooltip:AddDoubleLine("Latency (World)", string.format("%s%d", GetLatencyState(world), world))
	GameTooltip:AddDoubleLine("Latency (Home)", string.format("%s%d", GetLatencyState(home), home))

	GameTooltip:Show()
end

local TooltipUpdater = CreateFrame("Frame")
TooltipUpdater:Hide()
TooltipUpdater:SetScript("OnUpdate", UpdateTooltip)

function Plugin:OnEnter()
	GameTooltip:SetOwner(self, "ANCHOR_NONE")
	GameTooltip:ClearAllPoints()

	local x, y = GetCursorPosition()
	if (y * 2) > UIParent:GetHeight() then
		GameTooltip:SetPoint("TOP", self, "BOTTOM", 0, -10)
	else
		GameTooltip:SetPoint("BOTTOM", self, "TOP", 0, 10)
	end

	TooltipUpdater.owner = self
	TooltipUpdater:Show()
end

function Plugin:OnLeave()
	TooltipUpdater:Hide()
	TooltipUpdater.owner = nil
	GameTooltip:Hide()
end