Quantcast
local addon = CreateFrame'Frame'

local origs = {
	BNGetFriendInfo = BNGetFriendInfo,
	BNGetFriendInfoByID = BNGetFriendInfoByID
}
local origname = ""

UnitPopupButtons["BN_RENAME"] = { text = PET_RENAME, dist = 0 }
table.insert(UnitPopupMenus["BN_FRIEND"], 7, "BN_RENAME")
table.insert(UnitPopupMenus["BN_FRIEND_OFFLINE"], 2, "BN_RENAME")

local function UpdateName(origname, name)
	if name == origname or #name == 0 then
		MonikerDB[origname] = nil
	else
		MonikerDB[origname] = name
	end

	FriendsFrame_Update()
end

StaticPopupDialogs["BN_RENAME_FRIEND"] = {
	text = "Enter desired name of RealID friend or leave it empty if you want to use the original name",
	button1 = ACCEPT,
	button2 = CANCEL,
	hasEditBox = 1,
	hideOnEscape = 1,
	timeout = 0,
	exclusive = 1,

	OnAccept = function(self)
		local name = self.editBox:GetText()
		UpdateName(origname, name)
	end,

	EditBoxOnEnterPressed = function(self)
		local parent = self:GetParent()
		local name = parent.editBox:GetText()

		UpdateName(origname, name)
		parent:Hide()
	end,

	OnShow = function(self)
		local name = MonikerDB[origname] or ""
		self.editBox:SetText(name)
		self.editBox:SetFocus()
	end,
}

addon:RegisterEvent'VARIABLES_LOADED'
addon:SetScript('OnEvent', function()
	MonikerDB = MonikerDB or {}

	function BNGetFriendInfo(...)
		local pid, firstname, lastname = origs.BNGetFriendInfo(...)
		local name = firstname..' '..lastname

		if MonikerDB[name] then
			firstname = MonikerDB[name]
			lastname = ""
		end

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

	function BNGetFriendInfoByID(...)
		local pid, firstname, lastname = origs.BNGetFriendInfoByID(...)
		local name = firstname..' '..lastname

		if MonikerDB[name] then
			firstname = MonikerDB[name]
			lastname = ""
		end

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

	hooksecurefunc("UnitPopup_OnClick", function(self)
		local dropdown = UIDROPDOWNMENU_INIT_MENU;
		local button = self.value

		if button == "BN_RENAME" then
			local pid, firstname, lastname = origs.BNGetFriendInfoByID(dropdown.presenceID)
			local name = firstname..' '..lastname

			origname = name

			StaticPopup_Show"BN_RENAME_FRIEND"
		end
	end)
end)