import socket
import pickle
import server

class ServerLobby: 

	def __init__( self, server ):
		self.server = server
		self.users = server.address_to_user
		self.socket = server.socket

	def run( self ):

		while True:

			self.receive()


	def receive( self ):
		try: 
			data, address = self.socket.recvfrom( 1024 )

			unpickled_data = pickle.loads( data )

			if "JOIN" in unpickled_data:
				self.playerJoined( unpickled_data, address )

			elif "LEAVE" in unpickled_data:
				self.playerLeft( unpickled_data, address )

			elif "READY" in unpickled_data:
				self.playerReady( unpickled_data, address )

			elif "UNREADY" in unpickled_data:
				self.playerUnready( unpickled_data, address )

		except socket.error:
			return


	def send( self, data, name ):
		pickled_data = pickle.dumps( data )
		for address in self.users:
			if not name or name not in self.users[ address ]:
				print "Data sent to" + str( address )
				self.socket.sendto( pickled_data, address )


	def playerJoined( self, data, address ):
		colorKey = self.server.availableColors.keys()[0]
		color = self.server.availableColors.pop( colorKey, None )
		self.users[ address ] = server.Player( data["JOIN"], ( colorKey, color ) )

	def playerLeft( self, data, address ):
		player = self.users.pop( address, None )
		colorKey, color = player.color
		self.server.availableColors.update( {colorKey:color} )

	def playerReady( self, data, address ):
		player = self.users[ address ]
		player.ready = True

	def playerUnready( self, data, address ):
		player = self.users[ address ]
		player.ready = False

	def tryStartGame( self ):
		for user in self.users:
			if not user.ready:
				return 
		self.startGame()

	def startGame( self ):
		pass