require "Command.rb"
require "Commands.rb"

module RubyMud

class Exec < Command
	
	def words
		return ["exec"]
	end	

	def canUse?(object)
		return true if object.getFlagByClass(Admin)	!= nil or object.getFlagByClass(Builder) != nil
		return false
	end
	
	def initialize()
		super()
	end
	
	def feedBack(cc,string)
		cc.send(string+"\r\n")
	end
	
	def saveState(cc,name)		
		Players.removeAllPlayersFromRooms()
		f = File.new("SavedStates\\"+name, "wb")
		f.syswrite(Marshal.dump($rootRoom))
		f.close()
		cc.send("Saved state\r\n")		
		Players.putAllPlayersBackInRooms()
	end	
	
	def loadState(cc,name)
	
		# Clear the tick queues		
		TickQueue.clear()
		$mainTick.clear()
		TickObject.new($mainTick,Time.now+10)	

		# Deserialize the state
		f = File.new("SavedStates\\"+name, "rb") 
		s = f.stat 
		$rootRoom = Marshal.load(f.sysread(s.size))
		f.close()
		
		# Take the player to the root room
		cc.send("Transporting you to the root room\r\n")		
		cc.player.parent = $rootRoom
		$rootRoom.container.push(cc.player)		
		
		maxNum = 0
		# Call all the object' OnLoadMethod
		ObjectSpace.each_object do |object|
			if (object.is_a?(BaseObject))
				object.onLoad()
				(object.id > maxNum)? maxNum = object.id : 0		
			end
		end
		$autoNumber.set(maxNum+1)
	end		
	
	def execute(clientConnection,string)
		tokens = string.split(' ')

		# Cant execute nothing
		if (tokens.length == 1)
			clientConnection.send("You need to type something to execute\r\n")
			return
		end
		
		# Build the string to execute
		tokens.delete_at(0)
		execString = tokens.join(" ")
		clientConnection.send("Executing:"+execString+"\r\n")
		
		# Things evaluate can use
		currentPlayer = clientConnection.player
		currentRoom = clientConnection.player.parent
		cc = clientConnection
		
		# Execute it
		begin		
			eval(execString)
		rescue Exception => detail
		
			clientConnection.send("---------------------\r\n")
			clientConnection.send($!.to_s().gsub(/[\n]/, "\r\n")+"\r\n")
			clientConnection.send(detail.backtrace.join("\r\n"))
			clientConnection.send("\r\n")
			clientConnection.send("---------------------\r\n")
			clientConnection.send("\r\n")
		
		end
		
	end
		
end

# Create the instance, it adds itself to the commands list
Exec.new()

end #module