PartyStarter = {}

function PartyStarter:Inform(name)
	ZO_Alert(UI_ALERT_CATEGORY_ALERT, 1, "Attempting to invite ".. name)
end

function PartyStarter:ContextMenu(...)
	-- ok, lets let the menu generate, and add to the end
	self, playerName, rawName = ...
	zo_callLater(function() PartyStarter:AddLines(playerName, rawName) end, 1)
end

function PartyStarter:AddLines(playerName, rawName)
	local localPlayerIsGrouped = IsUnitGrouped("player")
    local localPlayerIsGroupLeader = IsUnitGroupLeader("player")

    if localPlayerIsGrouped or localPlayerIsGroupLeader then return end

    local menu = ZO_Menu.items
	local target = 0
	for i,v in ipairs(menu) do
		local label = GetControl(v.item, "Name")
		if label:GetText() == GetString(SI_CHAT_PLAYER_CONTEXT_ADD_GROUP) then
			target = i
		end
	end

 	-- If we can't find it, then lets add it
	if target == 0 then
		AddMenuItem(GetString(SI_CHAT_PLAYER_CONTEXT_ADD_GROUP), function() TryGroupInviteByName(playerName) end)
	else
		-- This is rather messy, we can't just move menu items around as they're all
		-- anchored to each other on -add-. So we just swap the functionality instead
		local storedFunc = menu[target].item.OnSelect
		local storedText = GetControl(menu[target].item, "Name"):GetText()

		local lastFunc = menu[#menu].item.OnSelect
		local lastText = GetControl(menu[#menu].item, "Name"):GetText()

		menu[target].item.OnSelect = lastFunc
		GetControl(menu[target].item, "Name"):SetText(lastText)
		menu[#menu].item.OnSelect = storedFunc
		GetControl(menu[#menu].item, "Name"):SetText(storedText)
   	end
	ShowMenu(nil, 1)
end

function PartyStarter:Loaded(...)
	local eventCode, addonName = ...
	if addonName ~= "PartyStarter" then return end

	ZO_PreHook(CHAT_SYSTEM, "ShowPlayerContextMenu", function(playerName, rawName) PartyStarter.ContextMenu(CHAT_SYSTEM, playerName, rawName) end)
	ZO_PreHook("TryGroupInviteByName", function(name) PartyStarter:Inform(name) end)
end



EVENT_MANAGER:RegisterForEvent("PartyStarterLoaded", EVENT_ADD_ON_LOADED, function(...) PartyStarter:Loaded(...) end)