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

local login_money = 0
local tooltip = nil

local goldInit = false
local goldLoaded = false
local player, realm, faction = UnitName("player"), GetCVar("realmName"), UnitFactionGroup("Player")

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


local function updateFactionRealm()
	if not goldDB[faction] then
			goldDB[faction] = {
				[realm]={
					[player]=0,
				},
			}
	elseif not goldDB[faction][realm] then
			goldDB[faction][realm]= {
				[player] = 0,
			}
	end
end

-- **************************************************************************
-- Function to initialise the saved variables.
-- **************************************************************************
local function gold_init_Array(self)
	if (goldInit == true) then 
		return
	elseif (not goldDB)  then
	 		goldDB={
				[faction]={
					[realm]={
						[player] = 0,
					},
				},
			}
			goldInit= true	
	else
		updateFactionRealm()
	end
	goldDB[faction][realm][player]= GetMoney()
end

--*******************************************
--	On Events, either get the current amount of money, or initialise the saved variables.
--*******************************************
local gold_onevent = function(self, event, addon)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Gold"])
	local current_money = GetMoney()

	if login_money == 0 then
		login_money = current_money
	end

	dataobj.text = GetCoinTextureString(current_money)

	if event == "ADDON_LOADED" then
		goldLoaded = true
		self:UnregisterEvent("ADDON_LOADED")
	end

	if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" or event == "ADDON_LOADED" then 
		if goldLoaded and (not goldDB) then 
			gold_init_Array()
		elseif goldInit == false then
			gold_init_Array()
		else 
			goldDB[faction][realm][player]= current_money
		end
    end

	if (event == "PLAYER_MONEY") then
       goldDB[faction][realm][player]= current_money
	end
	
	if event == "NEUTRAL_FACTION_SELECT_RESULT" then
		faction = UnitFactionGroup("Player")
		updateFactionRealm()
		goldDB[faction][realm][player]= GetMoney()
		goldDB["Neutral"][realm][player] = nil
	end
end

-- function to draw the tooltip.	
local function drawGoldTip()
	local now = GetMoney()
	local x = ''
	local totalGold = 0


	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 (" ")

	if goldLoaded then
	 	tooltip:AddLine(C.ltblue(string.format("%s %s", L["Total Gold on"], realm)), C.ltblue(faction))
		tooltip:AddSeparator()
		
		for k,v in func.pairsByKeys(goldDB[faction][realm]) do
			--local line, column = tooltip:AddLine(k, GetCoinTextureString(v)) 
			local line, column = tooltip:AddLine(k, GetCoinTextureString(v))
			tooltip:SetLineScript(line, "OnMouseUp", function(self) 
				if IsShiftKeyDown() then 
					goldDB[faction][realm][k] = nil 
					tooltip:Clear()
					drawGoldTip()
				end 
			end)			
			tooltip:SetLineScript(line, "OnEnter", function(self) tooltip:SetLineColor(line, 1,192/255, 90/255, 0.3) end )
			tooltip:SetLineScript(line, "OnLeave", function(self) tooltip:SetLineColor(line, 0,0,0,0) end)
			totalGold = totalGold + v
			line, column = nil, nil
		end
	end		
		tooltip:AddSeparator(2)
		tooltip:AddLine(L["Total Gold"], GetCoinTextureString(totalGold))
		tooltip:AddLine(" ")


	tooltip:AddLine(C.dkyellow(L["Session Statistics"]))
	tooltip:AddLine(string.format("%s:",L["Starting Amount"]), GetCoinTextureString(login_money))
	tooltip:AddLine(string.format("%s:", L["Current Amount"]), GetCoinTextureString(now))
	tooltip:AddSeparator()
	tooltip:AddLine(L["Profit / Loss this session"], x)
	tooltip:AddLine(" ")

	local line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Hint: Left-click to show the currency tab."]), nil, nil, 2)
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Shift-Click to remove entry."]), nil, nil, 2)
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', func.hideTooltip)
			else
					func.hideTooltip(tooltip)
			end
		end
	end

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

		func.createTooltip(self,tooltip)

	end
end

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


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

