from bge import logic, events
from threading import Thread
import socket
import pickle
import client
import clientGame

def initLobby( clientSocket, address, data ):

	client.setClientSocket( clientSocket )
	client.setClientData( data["CONNECTED"] )
	client.setServerAddress( address )

	logic.sendMessage( "initLobby", "", "ScriptRunnerConnect", "")

def start():
	scene = logic.getCurrentScene()
	data = client.getClientData()

	client.setClientColor( str( data["CLIENT_COLOR"] ) ) 

	addressField = scene.objects["Address"]
	serverAddress = client.getServerAddress()
	ip = serverAddress[0]
	port = serverAddress[1]

	addressField["Text"] = str( ip ) + " : " + str( port )

	gameTimeField = scene.objects["GameTime"]
	gameTimeField["Text"] = "Round Time: " + str( data["GAMETIME"] )
	players = data["PLAYERS"]

	for player in players:
		playerAttr = players[ player ]
		color = playerAttr["COLOR"]
		isReady = playerAttr["P_READY"]
		addPlayer( scene, player, color, isReady )

	logic.sendMessage( "receive", "", "ScriptRunnerLobby", "")

def addPlayer( scene, name, color, isReady ):
	spawner = scene.objects["Spawner" + color ]
	player = scene.addObject( "Sphere" + color, spawner )

	for child in player.children:
		if "Text" in child.name:
			child["Text"] = name

	setPlayerReady( scene, color, isReady )

def setPlayerReady( scene, color, isReady ):
	player = scene.objects["Sphere" + color]
	for child in player.children:
		if "Ready" in child.name:
			if isReady == True:
				child.setVisible( True, False )
			else:
				child.setVisible( False, False )

def receive():
	try:
		data, address = client.getClientSocket().recvfrom( 2048 )
		unpickled_data = pickle.loads( data )
		print(unpickled_data)
		if "JOIN" in unpickled_data:
			print("JOIN")
			playerJoined( unpickled_data["JOIN"] )

		elif "LEAVE" in unpickled_data:
			print("LEAVE")
			playerLeft( unpickled_data["LEAVE"] )

		elif "READY" in unpickled_data:
			print("READY")
			playerReady( unpickled_data["READY"] )

		elif "NOT_READY" in unpickled_data:
			print("NOT_READY")
			playerNotReady( unpickled_data["NOT_READY"] )

		elif "START_GAME" in unpickled_data:
			print("START_GAME")
			gameStarted( unpickled_data["START_GAME"] )

	except socket.error:
		pass

	logic.sendMessage( "receive", "", "ScriptRunnerLobby", "")

def sendReady():
	scene = logic.getCurrentScene()
	readySensor = scene.objects["ReadySensor"]
	if readySensor["active"] == False:
		return
	readySensor["active"] = False

	notReadySensor = scene.objects["NotReadySensor"]
	notReadySensor["active"] = True

	scene.objects["Ready"].setVisible( False, False )
	scene.objects["NotReady"].setVisible( True, False )

	ready_data = {"READY":None}
	pickled_data = pickle.dumps( ready_data, 2 )

	client.getClientSocket().sendto( pickled_data, client.getServerAddress() )

def sendNotReady():
	scene = logic.getCurrentScene()
	notReadySensor = scene.objects["NotReadySensor"]
	if notReadySensor["active"] == False:
		return
	notReadySensor["active"] = False

	readySensor = scene.objects["ReadySensor"]
	readySensor["active"] = True

	scene.objects["Ready"].setVisible( True, False )
	scene.objects["NotReady"].setVisible( False, False )

	ready_data = {"NOT_READY":None}
	pickled_data = pickle.dumps( ready_data, 2 )

	client.getClientSocket().sendto( pickled_data, client.getServerAddress() )

def playerJoined( data ):
	scene = logic.getCurrentScene()
	name = data["NAME"]
	color = data["COLOR"]

	addPlayer( scene, name, color, False )

def playerLeft( color ):
	scene = logic.getCurrentScene()
	
	playerObj = scene.objects[ "Sphere" + color ]
	playerObj.endObject()

def playerReady( color ):
	scene = logic.getCurrentScene()
	setPlayerReady( scene, color, True )

def playerNotReady( color ):
	scene = logic.getCurrentScene()
	setPlayerReady( scene, color, False )

def sendLeaveGame():
	leave_data = {"LEAVE":None}
	pickled_data = pickle.dumps( ready_data, 2 )

	client.getClientSocket().sendto( pickled_data, client.getServerAddress() )

def gameStarted( data ):
	print("started")
	Thread( target=clientGame.initGame, args=[ client.getClientSocket(), client.getServerAddress(), data ] ).start()