------------
-- Edited by Ekaterine @ Saurfang, based off Titan Gold Tracker.
------------

local C = Broker_Everything.color
local login_money = 0
local tooltip = nil

local goldInit = false
local goldAddonFired = false
local goldPlayer = UnitName("player").."_"..GetCVar("realmName").."::"..UnitFactionGroup("Player");

-- **************************************************************************
-- Function to initialise the Global Gold Array.
-- **************************************************************************
local function gold_init_Array(self)
	if (goldInit == true) then return
	else
		if (not beGoldArray) then
	 		beGoldArray={};
			beGoldArray["INITIALIZED"] = true
			beGoldArray["SORTBYNAME"] = true
			beGoldArray[goldPlayer] = GetMoney()
			goldInit = true		
		else beGoldArray[goldPlayer] = GetMoney()

		end
	end        
end

local gold_onevent = function(self, event)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["GOLD"])
	if login_money == 0 then
		login_money = GetMoney()
	end

	dataobj.text = GetCoinTextureString(GetMoney()) --

	if event == "ADDON_LOADED" then
		goldAddonFired = true
	end

	if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" or event == "ADDON_LOADED" then 
		if (goldAddonFired) and (not beGoldArray) then 
			gold_init_Array()
		else
			goldInit = true
			beGoldArray[goldPlayer] = GetMoney();
		end
    	end

	if (event == "PLAYER_MONEY") then
               beGoldArray[goldPlayer] = GetMoney();
	end
end


local gold_events = {
	"PLAYER_LOGIN",
	"PLAYER_MONEY",
	"PLAYER_TRADE_MONEY",
	"TRADE_MONEY_CHANGED",
	"PLAYER_ENTERING_WORLD",
	"ADDON_LOADED"
}

-- function to draw the tooltip.	
local function drawGoldTip()
	local now = GetMoney()
	local x = ''
	-------------
	-- Inserted by Ekaterina to track gold across multiple characters
	-------------
	local server = GetCVar("realmName").."::"..UnitFactionGroup("Player");
	local beGoldArraySorted = {};
	local totalGold = 0
	
	if goldAddonFired then 
		for index, money in pairs(beGoldArray) do
			local character, charserver = string.match(index, '(.*)_(.*)');
			if (character) then
				if (charserver == server) then
					table.insert(beGoldArraySorted, index); -- insert all keys from hash into the array
				end
			end
		end

		if (beGoldArray["SORTBYNAME"]) then
			table.sort(beGoldArraySorted);
		else
			table.sort(beGoldArraySorted, function (key1, key2) return beGoldArray[key1] > beGoldArray[key2] end) 
		end
	end
	------------
	-- End Insertion
	------------

	if now == login_money then
		x = GetCoinTextureString(0)
	elseif now > login_money then
		x = C.dkgreen("+" .. GetCoinTextureString(now - login_money))
	else
		x = C.red("-" .. GetCoinTextureString(login_money - now))
	end
	
	tooltip:AddHeader(C.dkyellow(L["Gold Information"]))
	tooltip:AddLine (" ")

	-----------
	-- Start insertion and modification of tooltip
	-----------
	if goldAddonFired then
	 	tooltip:AddLine(C.ltblue(L["CHARACTERGOLD"]), C.ltblue(string.format("%s : %s", GetCVar("realmName"), UnitFactionGroup("Player"))))
		tooltip:AddSeparator()
		for i = 1, getn(beGoldArraySorted) do 
			local character, charserver = string.match(beGoldArraySorted[i], '(.*)_(.*)');
			if character then
				if (charserver == server) then
					tooltip:AddLine(character, GetCoinTextureString(beGoldArray[beGoldArraySorted[i]])) 
					totalGold = totalGold + beGoldArray[beGoldArraySorted[i]]                
				end
			end
		end

		tooltip:AddSeparator()
		tooltip:AddLine(L["TOTALGOLD"], GetCoinTextureString(totalGold))
		tooltip:AddLine(" ")
	end

	tooltip:AddLine(C.dkyellow(L["Session Statistics"]))
	tooltip:AddLine(string.format("%s:",L["STARTGOLD"]), GetCoinTextureString(login_money))
	tooltip:AddLine(string.format("%s:", L["CURRENTGOLD"]), GetCoinTextureString(now))
	tooltip:AddSeparator()
	tooltip:AddLine(L["PROFITLOSS"], x)
	tooltip:AddLine(" ")

	local line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["GOLDHINTLEFT"]), nil, nil, 2)
end

-- function to hide the tooltip, if the mouse isn't over it.
local function hideTooltip()
	if MouseIsOver(tooltip) then return end
  
	tooltip:SetScript('OnLeave', nil)
	LibQTip:Release(tooltip)
	tooltip = nil
end

local gold_init = function(obj)
	if not obj then return end

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

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

	obj.OnEnter = function(self)
		tooltip = LibQTip:Acquire("GoldTT", 2, "LEFT", "RIGHT") 
		tooltip:SetScale(1)

		drawGoldTip()

		tooltip:SmartAnchorTo(self)
		tooltip:UpdateScrolling()
		tooltip:Show()

	end
end

local gold_onclick = function()
	ToggleCharacter("TokenFrame")
end


Broker_Everything:Register(L["GOLD"],
	"Interface\\Minimap\\TRACKING\\Auctioneer", --GetItemIcon(43641),
	gold_init,
	gold_onevent,
	gold_events,
	gold_onclick,
	0, --gold_tooltip,
	nil,
	nil)
