Quantcast
local addonname, addon = ...
local L = addon.L

addon.hooks = {}

local function ReplaceText(frame)
	if frame and frame.GetText and frame.SetText then
		local text = frame:GetText()
		if not text then return end

		for orig, nick in addon:IterNicknames() do
			if text:find(orig, nil, true) then
				return frame:SetText(text:gsub(orig, nick))
			end
		end
	end
end

local function ReplaceLink(text)
	return text:gsub("|HBNplayer:(.-):(.-):(.-):(.-):(.-)|h%[(.+)%]|h", function(a1, a2, a3, a4, a5, a6)
		return ("|HBNplayer:%s:%s:%s:%s:%s|h[%s]|h"):format(a1, a2, a3, a4, a5, addon:GetNicknameByPID(a1) or a6)
	end)
end

function addon.hooks.chat()
	local origs = {}

	local function AddMessage(self, text, ...)
		return origs[self](self, ReplaceLink(text), ...)
	end

	local function HookChatFrame(cf)
		if not origs[cf] then
			origs[cf] = cf.AddMessage
			cf.AddMessage = AddMessage
		end
	end

	hooksecurefunc("FCF_SetWindowName", function(frame, name, ...)
		HookChatFrame(frame)
		ReplaceText(_G[frame:GetName().."Tab"])
	end)

	for i = 1, NUM_CHAT_WINDOWS do
		HookChatFrame(_G["ChatFrame"..i])
	end
end

function addon.hooks.friendsframe()
	-- Hook tooltips
	FriendsTooltip:HookScript("OnShow", function(self)
		ReplaceText(FriendsTooltipHeader)
	end)

	BNToastFrame:HookScript("OnShow", function(self)
		ReplaceText(BNToastFrameTopLine)
	end)

	hooksecurefunc("HybridScrollFrame_Update", function(self)
		if self == FriendsFrameFriendsScrollFrame then
			local buttons = FriendsFrameFriendsScrollFrame.buttons

			for i, button in ipairs(buttons) do
				if button.buttonType == FRIENDS_BUTTON_TYPE_BNET then
					ReplaceText(button.name)
				end
			end
		end
	end)

	hooksecurefunc("FriendsFrameTooltip_Show", function(self)
		ReplaceText(FriendsTooltipHeader)
	end)

	hooksecurefunc("FriendsFrame_ShowBNDropdown", function(...)
		ReplaceText(DropDownList1Button1)
	end)

	hooksecurefunc("FriendsFriendsList_Update", function()
		ReplaceText(FriendsFriendsFrameTitle)

		for i = 1, FRIENDS_FRIENDS_TO_DISPLAY do
			local frame = _G["FriendsFriendsButton"..i]
			if frame then
				ReplaceText(frame.name)
			end
		end
	end)

	hooksecurefunc("BNConversationInvite_Update", function()
		for i = 1, BN_CONVERSATION_INVITE_NUM_DISPLAYED do
			local frame = _G["BNConversationInviteDialogListFriend"..i]
			if frame then
				ReplaceText(frame.name)
			end
		end
	end)

	hooksecurefunc(StaticPopupDialogs["SET_BNFRIENDNOTE"], "OnShow", function(self)
		ReplaceText(self.text)
	end)

	addon:Update()
end