GuildChat = {}

local LC = LibStub('libChat-1.0')
local LGI = LibStub("LibGuildInfo-1.0")

local AllianceColours = { ["Aldmeri Dominion"] = "|cffff00", ["Daggerfall Convenant"]= "|c4169E1", ["Ebonhart Pact"] = "|c8B0000"}
local ClassColours = {["Dragon Knight"] = "ca0000", ["Sorcerer"] = "0096ff", ["Nightblade"] = "9900f1", ["Templar"] = "efefef"}

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

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

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

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

function GuildChat:GetPrintName(name)
	if GuildChat.settings.characterName then
		local guildmember = LGI:GetGuildMemberByMemberName("@" ..name)
		return guildmember and guildmember.characterName or name
	end
	return 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, charname, name = nameLink:match("^|H([^:]-):([^\[]-)%[([^@]-)@([^\]]-)%]|h")
		if colour then
			formattedName = "[" .. GuildChat:GetLevelColour("@" .. name) .. GuildChat:GetLevel("@" .. name) .. "|c" .. baseColour:ToHex() .. "]" ..
							"[" .. (charname or "") .. GuildChat:GetAtColour("@" .. name) .."@" ..
							"|H" .. GuildChat:GetClassColour("@" .. name) .. ":" .. display .. GuildChat:GetPrintName(name) .. "|h" ..
							"|c" .. baseColour:ToHex() .. "]"
			end
	return formattedName or nameLink
end

function GuildChat:Register()
	LC:registerName(function(...) return GuildChat:GetName(...) end)
end

function GuildChat:Loaded(...)
	local eventId, addonName = ...
	if addonName ~= "GuildChat" then return end
	GuildChat.settings = ZO_SavedVars:NewAccountWide('GuildChat_Settings', 1, nil, {characterName = false})
	SLASH_COMMANDS["/gctogglecharname"] =
		function()
			GuildChat.settings.characterName = not GuildChat.settings.characterName
			d("GuildChat toggled to " .. (GuildChat.settings.characterName and "show character names" or "show account names"))
		end
	zo_callLater(GuildChat.Register, 1000)
end

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