local C = Broker_Everything.color
local tooltip = nil
local guildUpdateFreq = 300
local ttColumns = 5

-- function to refresh the guild roster cache
local function guildOnUpdate()
	if IsInGuild() then 
		GuildRoster()
	end
end

local guild_onevent = function (self, event, msg)
	local dataobj = self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L["GUILD"])
	if not IsInGuild() then
		dataobj.text = L["NOGUILD"]
		return
	end

	if CanViewOfficerNote() then ttColumns = 6 end

	if event == "PLAYER_LOGIN" or event == "PLAYER_ENTERING_WORLD" then
		GuildRoster()
	end

	if event == "CHAT_MSG_SYSTEM" then
		if string.find(msg, L["has come online"]) or string.find(msg, L["has gone offline"]) then
			
		end
	end

	if event == "GUILD_ROSTER_UPDATE" or event == "GUILD_XP_UPDATE" then
		local totalGuildMembers, membersOnline = GetNumGuildMembers()
		dataobj.text = membersOnline .. "/" .. totalGuildMembers
	end
end


guild_events = {
	"PLAYER_LOGIN",
	"GUILD_ROSTER_UPDATE",
	"PLAYER_ENTERING_WORLD",
	"GUILD_XP_UPDATE",
	"CHAT_MSG_SYSTEM"

}


-- Function to draw the guild tooltip
local function drawGuildTip()
	if not Broker_EverythingDB.GuildShowXP then Broker_EverythingDB["GuildShowXP"] = "yes" end

	if not IsInGuild() then
		tooltip:AddHeader(L["GUILD"])
		tooltip:AddLine(L["NOTINGUILD"])
		return
	end
-- XP & Reputation
	local currentXP, remainingXP, dailyXP, maxDailyXP = UnitGetGuildXP("player")
	local name, description, standingID, barMin, barMax, barValue = GetGuildFactionInfo()
	local factionStandingtext = GetText("FACTION_STANDING_LABEL"..standingID)
	local guildName = GetGuildInfo("player")
	local guildLevel = GetGuildLevel()

	local line, column = tooltip:AddHeader()
	tooltip:SetCell(line, 1, C.dkyellow(string.format("%s: <%s>", L["GUILD"], guildName)), nil, nil, ttColumns)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, string.format("%s %s: %d", L["GUILD"], L["LEVEL"], guildLevel), nil, nil, ttColumns)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.ltyellow(L["MOTD"]))
	tooltip:SetCell(line, 2, C.ltyellow(GetGuildRosterMOTD()), nil, nil, ttColumns - 1, LibQTip.LabelProvider, 5, 5, 50, 20)	

	tooltip:AddLine(" ")

	if Broker_EverythingDB.GuildShowXP == "yes" then 	
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, string.format("%s:", C.ltblue(L["XP"])))
		--tooltip:SetCell(line, 2, string.format("%s: %s.",  L["XPTNL"], TextStatusBar_CapDisplayOfNumericValue(remainingXP)), nil, nil, 2) -- xx xp to next level. 
		tooltip:SetCell(line, 2, string.format("%s/%s", TextStatusBar_CapDisplayOfNumericValue(currentXP), TextStatusBar_CapDisplayOfNumericValue(currentXP + remainingXP)),nil, nil, 2)
		
		if dailyXP == maxDailyXP then
			--line, column = tooltip:AddLine()
			tooltip:SetCell(line, 4, C.red(L["NOMOREXP"]), nil, nil, ttColumns-3) -- No more guild XP can be earned today.
		else
			--line, column = tooltip:AddLine()
			tooltip:SetCell(line, 4, string.format("%s: %s.",  L["MOREXP"], TextStatusBar_CapDisplayOfNumericValue(maxDailyXP - dailyXP)), nil, nil, ttColumns - 3)
		end		
		line, column = tooltip:AddLine()
		tooltip:SetCell(line, 1, string.format("%s:", C.ltblue(L["GUILDREP"])))
		tooltip:SetCell(line, 2, string.format("%s: (%d/%d)", factionStandingtext, barValue, barMax), nil, nil, ttColumns - 1)
		tooltip:AddLine(" ")
	end

		
	if ttColumns == 6 then
		tooltip:AddLine(C.ltyellow(L["LEVEL"]), C.ltyellow(L["ONLINE"]), C.ltyellow(L["ZONE"]), C.ltyellow(L["NOTES"]), C.ltyellow(L["ONOTES"]), C.ltyellow(L["RANK"]))
	else
		tooltip:AddLine(C.ltyellow(L["LEVEL"]), C.ltyellow(L["ONLINE"]), C.ltyellow(L["ZONE"]), C.ltyellow(L["NOTES"]), C.ltyellow(L["RANK"]))
	end

	tooltip:AddSeparator()
	local y = GetNumGuildMembers(true)
	for i = 1, y do
		local n, r, ri, l, c, z, no, ono, o, s, ec = GetGuildRosterInfo(i)
		if o then
			local name = string.format("%s %s", s or "", n)
		
			if ttColumns == 6 then
				line, column = tooltip:AddLine(l, C.className(name, ec), z or "",  no or "", ono or "" ,C.grey(r))
			else 
				line, column = tooltip:AddLine(l, C.className(name, ec), z or "",  no or "",C.grey(r))
			end
			tooltip:SetLineScript(line, "OnMouseUp", function(self) if IsAltKeyDown() then InviteUnit(n) else SetItemRef("player:"..name, "|Hplayer:"..name.."|h["..name.."|h", "LeftButton") end end, n)			
			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["GUILDHINT"]), nil, nil, 5)
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["GUILDHINTWHISPER"]), nil, nil, 5)
	
	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["GUILDHINTINVITE"]), nil, nil, 5)

	line, column = tooltip:AddLine()
	tooltip:SetCell(line, 1, C.dkgreen(L["GUILDHINTRIGHT"]), nil, nil, 5)
	
	line, column = nil, nil
	

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


 -- function to set onenter and onleave functions.
local guild_init = function(obj)
	if not obj then return end

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

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

	obj.OnEnter = function(self)
		if ttColumns == 6 then
			tooltip = LibQTip:Acquire("GuildTT", 6, "LEFT", "LEFT", "CENTER", "LEFT", "LEFT", "LEFT") 
		else
			tooltip = LibQTip:Acquire("GuildTT", 5, "LEFT", "LEFT", "CENTER", "LEFT" ,"LEFT") 
		end
		tooltip:Clear()
		tooltip:SetScale(1)

		drawGuildTip()

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

	end
end


local guild_onclick = function(self, btn)
	if btn == "RightButton" then 
		if Broker_EverythingDB.GuildShowXP == "yes" then 
			Broker_EverythingDB.GuildShowXP = "no"
		else
			Broker_EverythingDB.GuildShowXP = "yes"
		end

		if tooltip ~= nil then
			tooltip:Clear()
			drawGuildTip()
		end 
	elseif GUILockDown == nil then 
		ToggleGuildFrame()
	elseif GUILockDown == 1 then 
		return 
	end
end


Broker_Everything:Register(L["GUILD"],
	GetItemIcon(5976),
	guild_init,
	guild_onevent,
	guild_events,
	guild_onclick,
	0,
	guildOnUpdate,
	guildUpdateFreq)

