#    This file is part of CatchX.
#
#    CatchX is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    CatchX is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with CatchX.  If not, see <http://www.gnu.org/licenses/>.

#import stuff
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import threading

class gserver(threading.Thread): 

	def __init__(self): 
		threading.Thread.__init__(self) 
		self.run()
        
	class RequestHandler(SimpleXMLRPCRequestHandler):
		rpc_paths = ('/RPC2',)

	def run(self):
		#Set variables we'll need during the game
		self.players = 0
		self.playernames = ()
		self.game_started = False
		self.sv_password = "hackme" #To be loaded dynamically later...
		# Create server
		server = SimpleXMLRPCServer(("", 20211),
					requestHandler=self.RequestHandler)
		server.register_introspection_functions()
		
		# The main function of the server
		def sf_ping():
			return "pong"

		def sf_running():
			return self.game_started
		
		def sf_connect():
			self.players += 1
			return self.players #The unique player id
			
		def sf_auth(pid, password, name):
			if password == self.sv_password:
				self.playernames += ((name,self.players),)
				return True
			else:
				return False
		
		def sf_get_players(pid):
			return self.playernames
			
		def sf_keepalive(pid): # To be improved
			return True
		
		server.register_function(sf_ping, 'ping')
		server.register_function(sf_running, 'running')
		server.register_function(sf_connect, 'connect')
		server.register_function(sf_auth, 'auth')
		server.register_function(sf_get_players, 'get_players')
		server.register_function(sf_keepalive, 'keepalive')
		print("Server started @ Port 20211")
		
		# Run the server's main loop
		server.serve_forever()

#If the server runs standalone, automatically start it
if __name__ == "__main__":
	gserver()
