GuildChat = {}

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

local LGI = LibStub("LibGuildInfo-1.0")

local AllianceColours = { ["Aldmeri Dominion"] = "|cffff00", ["Daggerfall Convenant"]= "|c4169E1", ["Ebonhart Pact"] = "|c8B0000"}
local ClassColours = {["Dragon Knight"] = "ff0000", ["Sorcerer"] = "00ffff", ["Nightblade"] = "FF8C00", ["Templar"] = "FF00FF"}

function GuildChat:GetLevel(name)
	return LGI:GetLevelByMemberName(name)
end

function GuildChat:GetClassColour(name)
	return ClassColours[LGI:GetClassNameByMemberName(name)]
end

function GuildChat:GetLevelColour(name)
	return "|c9932CC"
end

function GuildChat:GetAtColour(name)
	return AllianceColours[LGI:GetAllianceNameByMemberName(name)]
end

local ChanInfoArray = ZO_ChatSystem_GetChannelInfo()
local CategoryMapping = ZO_ChatSystem_GetEventCategoryMappings()

function GuildChat:GetName(channelId, fromName, text)
	local info = ChanInfoArray[channelId]
	local r,g,b = GetChatCategoryColor(CategoryMapping[EVENT_CHAT_MESSAGE_CHANNEL][channelId])
	local baseColour = ZO_ColorDef:New(r, g, b, 1)

	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 = "[" .. GuildChat:GetLevelColour(fromName) .. GuildChat:GetLevel(fromName) .. "|c" .. baseColour:ToHex() .. "]" ..
							"[" .. GuildChat:GetAtColour(fromName) .. "@" ..
							"|H" .. GuildChat:GetClassColour(fromName) .. ":" .. display .. name .. "|h" ..
							"|c" .. baseColour:ToHex() .. "]"
			end
	return formattedName or nameLink
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)