GuildChat = {}

local LC = LibStub('libChat-1.0')
LC:registerName(function(...) return GuildChat:GetName(...) end)

function GuildChat:GetLevel(name)
	return "29"
end

function GuildChat:GetClassColour(name)
	return "ff1122"
end

function GuildChat:GetLevelColour(name)
	return "ff8100"
end

function GuildChat:GetAtColour(name)
	return "aa8100"
end

function GuildChat:GetName(channelId, fromName, text)

	local ChanInfoArray = ZO_ChatSystem_GetChannelInfo()
	local info = ChanInfoArray[channelId]
	local nameLink = (info.playerLinkable and not fromName:find("%[")) and ZO_LinkHandler_CreatePlayerLink(fromName:gsub("%^.+", "")) or fromName

	local formattedName = nil

	local  colour, display, name = nameLink:match("^|H([^:]*):([^\[]*)%[@([^\]]*)%]|h")
		if colour then
			formattedName = "|H"..colour.. ":".. display.."|h" ..
							"|H" .. colour ..":" .. display .. "[|h"..
							"|H" .. GuildChat:GetLevelColour(name) ..":" .. display .. GuildChat:GetLevel(name) .. "|h" ..
							"|H" .. colour ..":" .. display .. "][|h"..
							"|H" .. GuildChat:GetAtColour(name) .. ":".. display .. "@|h" ..
							"|H" .. GuildChat:GetClassColour(name) ..":" .. display .. name .."|h" ..
							"|H" .. colour ..":" .. display .. "]|h"
			end
	return formattedName or nameLink
end

function GuildChat:HookChat()

	if GuildChat.ChatFunction then return end

	if not CHAT_SYSTEM["containers"] then d("calling again") return zo_callLater(GuildChat.HookChat, 3000) end

	GuildChat.ChatFunction = CHAT_SYSTEM["containers"][1].AddMessageToWindow
	CHAT_SYSTEM["containers"][1].AddMessageToWindow =
		function(self, window, message, r, g, b, category)
			-- |Hignore:channel:My Guild Channel|h[My Guild Channel]|h|Hignore:display:SnuuSnuu|h[@SnuuSnuu]|h
			-- (|Hignore:channel:My Guild Channel|h[My Guild Channel]|h)|H(ignore):(display:SnuuSnuu|h)[@(SnuuSnuu)]|h
			local channel, colour, display, name, chat = message:match("^(.*)|H([^:]*):([^\[]*)%[@([^\]]*)%]|h(.*)")
			if channel then
				message = channel .."|H"..colour.. ":".. display.."|h" ..
							"|H" .. colour ..":" .. display .. "[|h"..
							"|H" .. GuildChat:GetLevelColour(name) ..":" .. display .. GuildChat:GetLevel(name) .. "|h" ..
							"|H" .. colour ..":" .. display .. "][|h"..
							"|H" .. GuildChat:GetAtColour(name) .. ":".. display .. "@|h" ..
							"|H" .. GuildChat:GetClassColour(name) ..":" .. display .. name .."|h" ..
							"|H" .. colour ..":" .. display .. "]|h".. chat
			end
			GuildChat.ChatFunction(self, window, message, r,g,b, category)
		end
end


function GuildChat:Loaded(...)
	local eventId, addonName = ...
	if addonName ~= "GuildChat" then return end
end

EVENT_MANAGER:RegisterForEvent("GuildChatLoaded", EVENT_ADD_ON_LOADED, function(...) GuildChat:Loaded(...) end)