Quantcast
local addonname, addon = ...
local loaddelay = 1.5

Moniker = addon

function addon:Initialize()
	self.frame = CreateFrame"Frame"
	self.frame:SetScript("OnEvent", function(frame, event, ...)
		if self[event] then
			self[event](addon, ...)
		end
	end)

	self.frame:RegisterEvent"ADDON_LOADED"
	self.frame:RegisterEvent"BN_FRIEND_INFO_CHANGED"
end


function addon:ADDON_LOADED(loaded)
	if loaded ~= addonname then return end

	self.nicks = {}

	for i = 1, BNGetNumFriends() do
		self:BN_FRIEND_INFO_CHANGED(i)
	end

	local elapsed = 0
	self.frame:SetScript("OnUpdate", function(frame, e)
		elapsed = elapsed + e
		if elapsed > loaddelay then
			frame:SetScript("OnUpdate", nil)

			self:CreateHooks()
		end
	end)
end

function addon:BN_FRIEND_INFO_CHANGED(i)
	if not i then return end

	local _, firstname, lastname, _, _, _, _, _, _, _, _, note = BNGetFriendInfo(i)
	local name = BATTLENET_NAME_FORMAT:format(firstname, lastname)

	if note and #note > 0 then
		self.nicks[name] = note
	else
		self.nicks[name] = nil
	end

	self:Update()
end

function addon:Update()
	if not InCombatLockdown() then
		FriendsFrame_UpdateFriends()
	end
end

function addon:CreateHooks()
	for n, func in pairs(self.hooks) do
		func()
	end
end

function addon:GetNickname(name)
	return self.nicks[name]
end

function addon:GetNicknameByPID(pid)
	if type(pid) == "string" then
		pid = pid:match"|Kf(%d+)|k"
		if pid then
			pid = tonumber(pid)
		end
	end

	if type(pid) == "number" then
		local nickname = select(2, Moniker_BNGetFriendInfoByID(pid))
		return nickname
	end
end

function addon:SetNickname(name, nickname)
	if name == nickanme or #nickname == 0 then
		nickname = nil
	end

	self.nicks[name] = nickname
	self:Update()
end

function addon:IterNicknames()
	return pairs(self.nicks)
end

function Moniker_BNGetFriendInfo(...)
	local pid, firstname, lastname = BNGetFriendInfo(...)
	local name = BATTLENET_NAME_FORMAT:format(firstname, lastname)
	local nickname = addon:GetNickname(name)

	if nickname then
		firstname = nickname
		lastname = ""
	end

	return pid, firstname, lastname, select(4, BNGetFriendInfo(...))
end

function Moniker_BNGetFriendInfoByID(...)
	local pid, firstname, lastname = BNGetFriendInfoByID(...)
	local name = BATTLENET_NAME_FORMAT:format(firstname, lastname)
	local nickname = addon:GetNickname(name)

	if nickname then
		firstname = nickname
		lastname = ""
	end

	return pid, firstname, lastname, select(4, BNGetFriendInfoByID(...))
end

addon:Initialize()