local C=game:GetService("\082\117\110\083\101\114\118\105\099\101")local O=game:GetService("\080\108\097\121\101\114\115")local V=require(script.Parent.Argument)local L=C:IsServer()local j={}j.__index=j function j.new(C)local O={Dispatcher=C.Dispatcher;Cmdr=C.Dispatcher.Cmdr;Name=C.CommandObject.Name;RawText=C.Text;Object=C.CommandObject;Group=C.CommandObject.Group,State={},Aliases=C.CommandObject.Aliases,Alias=C.Alias,Description=C.CommandObject.Description,Executor=C.Executor,ArgumentDefinitions=C.CommandObject.Args;RawArguments=C.Arguments;Arguments={},Data=C.Data,Response=nil}setmetatable(O,j)return O end function j.Parse(O,C)local L=false for j,W in ipairs(O.ArgumentDefinitions)do if type(W)=="\102\117\110\099\116\105\111\110"then W=W(O)if W==nil then break end end local y=W.Default==nil and W.Optional~=true if y and L then error(("\067\111\109\109\097\110\100 \037\113\058 \082\101\113\117\105\114\101\100 \097\114\103\117\109\101\110\116\115 \099\097\110\110\111\116 \111\099\099\117\114 \097\102\116\101\114 \111\112\116\105\111\110\097\108 \097\114\103\117\109\101\110\116\115\046"):format(O.Name))elseif not y then L=true end if O.RawArguments[j]==nil and(y and C~=true)then return false,("\082\101\113\117\105\114\101\100 \097\114\103\117\109\101\110\116 \035\037\100 \037\115 \105\115 \109\105\115\115\105\110\103\046"):format(j,W.Name)elseif O.RawArguments[j]or C then O.Arguments[j]=V.new(O,W,O.RawArguments[j]or"")end end return true end function j.Validate(O,C)O._Validated=true local V=""local L=true for O,j in pairs(O.Arguments)do local W,y=j:Validate(C)if not W then L=false V=("\037\115\059 \035\037\100 \037\115\058 \037\115"):format(V,O,j.Name,y or"\101\114\114\111\114")end end return L,V:sub(3)end function j.GetLastArgument(C)for O=#C.Arguments,1,-1 do if C.Arguments[O].RawValue then return C.Arguments[O]end end end function j.GatherArgumentValues(C)local O={}for V=1,#C.ArgumentDefinitions,1 do local L=C.Arguments[V]if L then O[V]=L:GetValue()elseif type(C.ArgumentDefinitions[V])=="\116\097\098\108\101"then O[V]=C.ArgumentDefinitions[V].Default end end return O,#C.ArgumentDefinitions end function j.Run(C)if C._Validated==nil then error("\077\117\115\116 \118\097\108\105\100\097\116\101 \097 \099\111\109\109\097\110\100 \098\101\102\111\114\101 \114\117\110\110\105\110\103\046")end local O=C.Dispatcher:RunHooks("\066\101\102\111\114\101\082\117\110",C)if O then return O end if not L and(C.Object.Data and C.Data==nil)then local O,V=C:GatherArgumentValues()C.Data=C.Object.Data(C,unpack(O,1,V))end if not L and C.Object.ClientRun then local O,V=C:GatherArgumentValues()C.Response=C.Object.ClientRun(C,unpack(O,1,V))end if C.Response==nil then if C.Object.Run then local O,V=C:GatherArgumentValues()C.Response=C.Object.Run(C,unpack(O,1,V))elseif L then if C.Object.ClientRun then warn(C.Name,"\099\111\109\109\097\110\100 \102\101\108\108 \098\097\099\107 \116\111 \116\104\101 \115\101\114\118\101\114 \098\101\099\097\117\115\101 \067\108\105\101\110\116\082\117\110 \114\101\116\117\114\110\101\100 \110\105\108\044 \098\117\116 \116\104\101\114\101 \105\115 \110\111 \115\101\114\118\101\114 \105\109\112\108\101\109\101\110\116\097\116\105\111\110\033 \069\105\116\104\101\114 \114\101\116\117\114\110 \097 \115\116\114\105\110\103 \102\114\111\109 \067\108\105\101\110\116\082\117\110\044 \111\114 \099\114\101\097\116\101 \097 \115\101\114\118\101\114 \105\109\112\108\101\109\101\110\116\097\116\105\111\110 \102\111\114 \116\104\105\115 \099\111\109\109\097\110\100\046")else warn(C.Name,"\099\111\109\109\097\110\100 \104\097\115 \110\111 \105\109\112\108\101\109\101\110\116\097\116\105\111\110\033")end C.Response="\078\111 \105\109\112\108\101\109\101\110\116\097\116\105\111\110\046"else C.Response=C.Dispatcher:Send(C.RawText,C.Data)end end local V=C.Dispatcher:RunHooks("\065\102\116\101\114\082\117\110",C)if V then return V else return C.Response end end function j.GetArgument(O,C)return O.Arguments[C]end function j.GetData(C)if C.Data then return C.Data end if C.Object.Data and not L then C.Data=C.Object.Data(C)end return C.Data end function j.SendEvent(j,C,V,...)assert(typeof(C)=="\073\110\115\116\097\110\099\101","\065\114\103\117\109\101\110\116 \035\049 \109\117\115\116 \098\101 \097 \080\108\097\121\101\114")assert(C:IsA("\080\108\097\121\101\114"),"\065\114\103\117\109\101\110\116 \035\049 \109\117\115\116 \098\101 \097 \080\108\097\121\101\114")assert(type(V)=="\115\116\114\105\110\103","\065\114\103\117\109\101\110\116 \035\050 \109\117\115\116 \098\101 \097 \115\116\114\105\110\103")if L then j.Dispatcher.Cmdr.RemoteEvent:FireClient(C,V,...)elseif j.Dispatcher.Cmdr.Events[V]then assert(C==O.LocalPlayer,"\069\118\101\110\116 \109\101\115\115\097\103\101\115 \099\097\110 \111\110\108\121 \098\101 \115\101\110\116 \116\111 \116\104\101 \108\111\099\097\108 \112\108\097\121\101\114 \111\110 \116\104\101 \099\108\105\101\110\116\046")j.Dispatcher.Cmdr.Events[V](...)end end function j.BroadcastEvent(C,...)if not L then error("\067\097\110\'\116 \098\114\111\097\100\099\097\115\116 \101\118\101\110\116 \109\101\115\115\097\103\101\115 \102\114\111\109 \116\104\101 \099\108\105\101\110\116\046",2)end C.Dispatcher.Cmdr.RemoteEvent:FireAllClients(...)end function j.Reply(C,...)return C:SendEvent(C.Executor,"\065\100\100\076\105\110\101",...)end function j.GetStore(C,...)return C.Dispatcher.Cmdr.Registry:GetStore(...)end function j.HasImplementation(O)return(C:IsClient()and O.Object.ClientRun or O.Object.Run)and true or false end return j
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local Argument = require(script.Parent.Argument)

local IsServer = RunService:IsServer()

local Command = {}
Command.__index = Command

--// Returns a new CommandContext, an object which is created for every command validation.
-- This is also what's passed as the context to the "Run" functions in commands
function Command.new (options)
	local self = {
		Dispatcher = options.Dispatcher; -- The dispatcher that created this command context
		Cmdr = options.Dispatcher.Cmdr; -- A quick reference to Cmdr for command context
		Name = options.CommandObject.Name; -- The command name (not alias)
		RawText = options.Text; -- The raw text used to trigger this command
		Object = options.CommandObject; -- The command object (definition)
		Group = options.CommandObject.Group; -- The group this command is in
		State = {}; -- A table which will hold any custom command state information
		Aliases = options.CommandObject.Aliases;
		Alias = options.Alias; -- The command name that was used
		Description = options.CommandObject.Description;
		Executor = options.Executor; -- The player who ran the command
		ArgumentDefinitions = options.CommandObject.Args; -- The argument definitions from the command definition
		RawArguments = options.Arguments; -- Array of strings which are the unparsed values for the arguments
		Arguments = {}; -- A table which will hold ArgumentContexts for each argument
		Data = options.Data; -- A special container for any additional data the command needs to collect from the client
		Response = nil; -- Will be set at the very end when the command is run and a string is returned from the Run function.
	}

	setmetatable(self, Command)

	return self
end

--// Parses all of the command arguments into ArgumentContexts
-- Called by the command dispatcher automatically
-- allowIncompleteArguments: if true, will not throw an error for missing arguments
function Command:Parse (allowIncompleteArguments)
	local hadOptional = false
	for i, definition in ipairs(self.ArgumentDefinitions) do
		if type(definition) == "function" then
			definition = definition(self)

			if definition == nil then
				break
			end
		end

		local required = (definition.Default == nil and definition.Optional ~= true)

		if required and hadOptional then
			error(("Command %q: Required arguments cannot occur after optional arguments."):format(self.Name))
		elseif not required then
			hadOptional = true
		end

		if self.RawArguments[i] == nil and required and allowIncompleteArguments ~= true then
			return false, ("Required argument #%d %s is missing."):format(i, definition.Name)
		elseif self.RawArguments[i] or allowIncompleteArguments then
			self.Arguments[i] = Argument.new(self, definition, self.RawArguments[i] or "")
		end
	end

	return true
end

--// Validates that all of the arguments are in a valid state.
-- This must be called before :Run() is called.
-- Returns boolean (true if ok), errorText
function Command:Validate (isFinal)
	self._Validated = true
	local errorText = ""
	local success = true

	for i, arg in pairs(self.Arguments) do
		local argSuccess, argErrorText = arg:Validate(isFinal)

		if not argSuccess then
			success = false
			errorText = ("%s; #%d %s: %s"):format(errorText, i, arg.Name, argErrorText or "error")
		end
	end

	return success, errorText:sub(3)
end

--// Returns the last argument that has a value.
-- Useful for getting the autocomplete for the argument the user is working on.
function Command:GetLastArgument()
	for i = #self.Arguments, 1, -1 do
		if self.Arguments[i].RawValue then
			return self.Arguments[i]
		end
	end
end

--// Returns a table containing the parsed values for all of the arguments.
function Command:GatherArgumentValues ()
	local values = {}

	for i = 1, #self.ArgumentDefinitions do
		local arg = self.Arguments[i]
		if arg then
			values[i] = arg:GetValue()
		elseif type(self.ArgumentDefinitions[i]) == "table" then
			values[i] = self.ArgumentDefinitions[i].Default
		end
	end

	return values, #self.ArgumentDefinitions
end

--// Runs the command. Handles dispatching to the server if necessary.
-- Command:Validate() must be called before this is called or it will throw.
function Command:Run ()
	if self._Validated == nil then
		error("Must validate a command before running.")
	end

	local beforeRunHook = self.Dispatcher:RunHooks("BeforeRun", self)
	if beforeRunHook then
		return beforeRunHook
	end

	if not IsServer and self.Object.Data and self.Data == nil then
		local values, length = self:GatherArgumentValues()
		self.Data = self.Object.Data(self, unpack(values, 1, length))
	end

	if not IsServer and self.Object.ClientRun then
		local values, length = self:GatherArgumentValues()
		self.Response = self.Object.ClientRun(self, unpack(values, 1, length))
	end

	if self.Response == nil then
		if self.Object.Run then -- We can just Run it here on this machine
			local values, length = self:GatherArgumentValues()
			self.Response = self.Object.Run(self, unpack(values, 1, length))

		elseif IsServer then -- Uh oh, we're already on the server and there's no Run function.
			if self.Object.ClientRun then
				warn(self.Name, "command fell back to the server because ClientRun returned nil, but there is no server implementation! Either return a string from ClientRun, or create a server implementation for this command.")
			else
				warn(self.Name, "command has no implementation!")
			end

			self.Response = "No implementation."
		else -- We're on the client, so we send this off to the server to let the server see what it can do with it.
			self.Response = self.Dispatcher:Send(self.RawText, self.Data)
		end
	end

	local afterRunHook = self.Dispatcher:RunHooks("AfterRun", self)
	if afterRunHook then
		return afterRunHook
	else
		return self.Response
	end
end

--// Returns an ArgumentContext for the specific index
function Command:GetArgument (index)
	return self.Arguments[index]
end

-- Below are functions that are only meant to be used in command implementations --

--// Returns the extra data associated with this command.
-- This needs to be used instead of just context.Data for reliability when not using a remote command.
function Command:GetData ()
	if self.Data then
		return self.Data
	end

	if self.Object.Data and not IsServer then
		self.Data = self.Object.Data(self)
	end

	return self.Data
end

--// Sends an event message to a player
function Command:SendEvent(player, event, ...)
	assert(typeof(player) == "Instance", "Argument #1 must be a Player")
	assert(player:IsA("Player"), "Argument #1 must be a Player")
	assert(type(event) == "string", "Argument #2 must be a string")

	if IsServer then
		self.Dispatcher.Cmdr.RemoteEvent:FireClient(player, event, ...)
	elseif self.Dispatcher.Cmdr.Events[event] then
		assert(player == Players.LocalPlayer, "Event messages can only be sent to the local player on the client.")
		self.Dispatcher.Cmdr.Events[event](...)
	end
end

--// Sends an event message to all players
function Command:BroadcastEvent(...)
	if not IsServer then
		error("Can't broadcast event messages from the client.", 2)
	end

	self.Dispatcher.Cmdr.RemoteEvent:FireAllClients(...)
end

--// Alias of self:SendEvent(self.Executor, "AddLine", text)
function Command:Reply(...)
	return self:SendEvent(self.Executor, "AddLine", ...)
end

--// Alias of Registry:GetStore(...)
function Command:GetStore(...)
	return self.Dispatcher.Cmdr.Registry:GetStore(...)
end

--// Returns true if the command has an implementation on the caller's machine.
function Command:HasImplementation()
	return ((RunService:IsClient() and self.Object.ClientRun) or self.Object.Run) and true or false
end

return Command
