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

local tooltip = nil
local totalOnline = 0
local totalFriends = 0
local friends ={}

local friends_events = {
	--"PLAYER_LOGIN",
	"FRIENDLIST_UPDATE",
	"PLAYER_ENTERING_WORLD",
	"BN_FRIEND_ACCOUNT_ONLINE",
	"BN_FRIEND_ACCOUNT_OFFLINE",
}


local function grabFriends(self)
	local gameIcons = {
		[BNET_CLIENT_WOW] = "|TInterface\\FriendsFrame\\Battlenet-WoWicon:16:16:0:0:64:64:4:60:4:60|t",
		[BNET_CLIENT_SC2] = "|TInterface\\FriendsFrame\\Battlenet-Sc2icon:0|t",
		[BNET_CLIENT_D3]  = "|TInterface\\FriendsFrame\\Battlenet-D3icon:0:0:0:0:64:64:4:60:4:60|t",
	}
	
	local numBNFriends, numOnlineBNFriends = BNGetNumFriends()
	local numFriends, friendsOnline = GetNumFriends()
	local server = GetCVar("realmName")
	local englishFaction, localizedFaction = UnitFactionGroup("player")
	friends = wipe(friends)


	if numOnlineBNFriends >0 then
		for i = 1, numBNFriends, 1 do
			local presenceID, presenceName, battleTag, isBattleTagPresence, toonName, toonID, game, isOnline, lastOnline, isAFK, isDND, broadcastText, noteText, isFriend, broadcastTime, canSoR = BNGetFriendInfo(i)

			if isOnline == true then
				local _, _, _, realmName, realmID, faction, race, class, guild, area, level, gameText = BNGetToonInfo(presenceID)
				local status 
				if isAFK == true then
					status = "[AFK]"
				elseif isDND == true then 
					status = "[DND]"
				else
					status = ""
				end
				
				if toonName == nil or (not toonName) then
					toonName = presenceName
				end 
			
				friends[toonName] = {
					["battleNet"] = true,
					["presenceName"] = presenceName,
					["presenceID"] = presenceID,
					["battleTag"] = battleTag,
					["toonID"] = toonID,
					["client"] = client,
					["status"] = status,
					["game"] = gameIcons[game],
					["realm"] = realmName,
					["faction"] = faction,
					["class"] = strupper(class),
					["zone"] = area,
					["level"] = level,
					["notes"] = noteText or "",
					["online"] = isOnline,
				}
			end
		end
	end
	
	if numFriends > 0 then
		for i = 1, numFriends, 1 do
			local name, level, class, area, connected, status, note = GetFriendInfo(i)
			if status == 0 then
				status = ""
			elseif status== 1 then
				status = "[AFK]"
			elseif status == 2 then
				status = "[DND]"
			end
			
			if ((friends[name] == nil) or (not friends[name])) and name ~= nil then
				if connected == 1 then
					connected = true
				else
					connected = false
				end
				
				friends[name] = {
					["battleNet"] = false,
					["status"] = status,
					["game"] = gameIcons[BNET_CLIENT_WOW],
					["faction"] = localizedFaction or englishFaction,
					["realm"] = server,
					["class"] = strupper(class),
					["zone"]  = area,
					["level"] = level,
					["notes"] = note or " ",
					["online"] = connected,
				}

			end		
		end
	end
end


local friends_onevent = function (self)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["Social"])
	totalOnline = 0
	totalFriends = 0
	
	grabFriends()
	
	for k, v in pairs(friends) do 
		totalFriends = totalFriends + 1
		if v.online == true then
			totalOnline = totalOnline + 1
		end
	end
	
	dataobj.text = totalOnline .. "/" .. totalFriends
	
end


local function drawFriendsTip()
	--grabFriends()
	local line, column
	tooltip:AddHeader(C.dkyellow(L["Friends"]))

	if totalOnline == 0 then
		tooltip:AddLine(L["No Friends Online."])
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, C.dkgreen(L["Hint: Left-click to open the friends roster."]), nil, nil, 6)
		return
	end
	-- RealId	Status Character	Level	Zone	Game	Realm	Notes

	tooltip:AddLine(C.ltyellow(L["Real ID"]), C.ltyellow(L["BattleTag"]), C.ltyellow(L["Character"]), C.ltyellow(L["Level"]), C.ltyellow(L["Zone"]), C.ltyellow(L["Game"]), C.ltyellow(L["Realm"]), C.ltyellow(L["Faction"]), C.ltyellow(L["Notes"]))	
	tooltip:AddSeparator()
	
	for k,v in func.pairsByKeys(friends) do
		if v.online == true  then
			local name 
			if v.battleNet then 
				line, column = tooltip:AddLine(C.ltblue(v.presenceName), C.ltblue(v.battleTag or " "), C.className(v.status.. k, v.class), C.white(v.level), C.white(v.zone), v.game, C.white(v.realm), C.white(v.faction), C.white(v.notes or " "))
				tooltip:SetLineScript(line, "OnMouseUp", function(self) if IsAltKeyDown() then BNInviteFriend(v.toonID) else ChatFrame_SendSmartTell(v.presenceName) end end, n)	
			else
				line, column = tooltip:AddLine(" ", " ", C.className(v.status.. k, v.class), C.white(v.level), C.white(v.zone), C.white(v.game), C.white(v.realm), C.white(v.faction), C.white(v.notes or " "))
				tooltip:SetLineScript(line, "OnMouseUp", function(self) if IsAltKeyDown() then InviteUnit(k) else ChatFrame_SendTell(k) end end, n)
			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)
		end
	end
	tooltip:AddLine(" ")
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Hint: Left-click to open the friends roster."]), nil, nil, 7)
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Click a friend to whisper."]), nil, nil, 7)
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["Alt + Click a friend to invite."]), nil, nil, 7)

	line, column = nil, nil
end



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

	obj = obj.obj

	obj.OnLeave = function(self)
		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("FriendsTT", 9 , "LEFT", "LEFT", "LEFT", "CENTER", "CENTER", "CENTER", "CENTER", "LEFT", "LEFT" ) 
		drawFriendsTip()
		func.createTooltip(self,tooltip)
	end

end


local friends_onclick = function()
	ToggleFriendsFrame(1)
end


Broker_Everything:Register(L["Friends"],
	"Interface\\Addons\\Broker_Everything\\media\\friends",
	friends_init,
	friends_onevent,
	friends_events,
	friends_onclick,
	0,
	nil,
	nil)

