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


local xp_events = {
	"PLAYER_XP_UPDATE",
	"PLAYER_LOGIN",
}


local xp_init = function()
	if not Broker_EverythingDB[L["XP"]] then
		Broker_EverythingDB[L["XP"]] = {
		enabled = true,
		display = false,
		}
	elseif not Broker_EverythingDB[L["XP"]].display then
		Broker_EverythingDB[L["XP"]].display = false
	end
end


local xp_onevent = function(self)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["XP"])
	if Broker_EverythingDB[L["XP"]].display == false then
		dataobj.text = math.floor((UnitXP("player") / UnitXPMax("player")) * 100) .. "%"
	else
		dataobj.text = UnitXP("player") .. "/" ..  UnitXPMax("player")
	end
end


local xp_onclick = function(self, btn)
	if btn == "RightButton" then
		if Broker_EverythingDB[L["XP"]].display == false then
			Broker_EverythingDB[L["XP"]].display = true
		else
			Broker_EverythingDB[L["XP"]].display = false
		end
		xp_onevent(self)
	end
end


local xp_tooltip = function(t)
	local e, m = UnitXP("player"), UnitXPMax("player")
	local r = GetXPExhaustion()

	if not r then
		r = "0%"
	else
		r = floor((r / m) * 100) .. "%"
	end

	t:AddLine(L["XP"])
	t:AddLine(" ")
	t:AddDoubleLine(C.white(string.format("%s:", L["XP"])), C.white(string.format("%d/%d", e, m)))
	t:AddDoubleLine(C.white(string.format("%s:", L["Til Next Level"])), C.white(m - e))
	t:AddDoubleLine(C.white(string.format("%s:", L["Rest"])), C.white(r))
	t:AddLine(" ")
	t:AddLine(C.dkgreen(L["Hint: Right-click to switch display mode."]))
end


Broker_Everything:Register(L["XP"],
	"Interface\\Addons\\Broker_Everything\\media\\xp.tga", --GetItemIcon(24791),
	xp_init,
	xp_onevent,
	xp_events,
	xp_onclick,
	xp_tooltip,
	nil,
	nil)
