require(game.ReplicatedFirst.ReadyModule)("CommandsModule")

local help = ""
local commands = {}

function invoke(input,player)
	local found = false
	for index,command in ipairs(commands) do
		local result = table.pack(input:match(command.pattern))
		if result[1] then 
			if player then 
				table.insert(result,1,player)
			end 
			found = true
			command.callback(table.unpack(result))
		end
	end
	return found
end

function new(pattern,documentation,callback)
	help = help .. documentation .. "\n"
	table.insert(commands,{
		pattern = pattern,
		documentation = documentation,
		callback = callback
	})
	if _G.IsServer then _G.Storage:WaitForChild("CommandsHelp").Value = help end
end

_G.Events.Command.Event:Connect(function(command)
	local cFound = invoke(command)
	local sFound = _G.Remotes.Command:InvokeServer(command)
	if not cFound and not sFound then _G.Events.Notification:Fire("Command Not Found",[[
If you're struggling to type in a command, note that they use pattern matching.
"<userid>" means you should literally type "12345678", no letters or dots.
Check your spelling or type 'help' for some commands.
	]]) end
end)

if _G.IsServer then
	_G.Remotes.Command.OnServerInvoke = function(player,command)
		return invoke(command,player)
	end
end

local notification
new("help","help: displays this message",function()
	local final = "Client:\n"..help
	if _G.IsClient then final = final.."\nServer:\n".._G.Storage.CommandsHelp.Value end
	_G.Events.Notification:Fire("Command Help",final)
end)

return getfenv()