from bge import logic, events
from mathutils import Vector
import socket
import pickle
import client
import time
import random
import Rasterizer

def initGame( clientSocket, address, data ):
	client.setClientSocket( clientSocket )
	client.setClientData( data )
	client.setServerAddress( address )

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

def start( ):
	Rasterizer.showMouse( False )
	scene = logic.getCurrentScene( )
	data = client.getClientData()
	color = client.getClientColor()

	spawner = scene.objects[ "SpawnerGame" + color + str( 1 )]
	player = scene.addObject( "Character", spawner )

	for colorKey in data:
		if colorKey != color:
			spawner = scene.objects[ "SpawnerGame" + colorKey + str( 1 ) ]
			player = scene.addObject( "OtherPlayer", spawner )
			client.addOtherPlayer( colorKey, player )

	logic.sendMessage( "receive", "", "ClientScriptRunner", "" )
	logic.sendMessage( "sendUpdate", "", "ClientScriptRunner", "" )

def sendUpdate( ):
	scene = logic.getCurrentScene()
	character = scene.objects["Character"]
	
	location = resolveObjectData( character )
	send( { "PLAYER_UPDATE" : location } )

	logic.sendMessage( "sendUpdate", "", "ClientScriptRunner", "" )

def send( data ):
	pickled_data = pickle.dumps( data, 2 )
	client.getClientSocket().sendto( pickled_data, client.getServerAddress() )


def shoot( ):
	scene = logic.getCurrentScene()
	origin = scene.objects["CameraBox"]

	if time.clock() - origin["cooldown"] < 1:
		return
	origin["cooldown"] = time.clock()

	location = resolveObjectData( origin )
	send( { "PLAYER_SHOOT" : location } )

def resolveObjectData( obj ):
	pos = list( obj.worldPosition )
	vector_rot = list( obj.worldOrientation )
	rot = []
	for m in vector_rot:
		rot.append( list(m) )
	
	location = { "POS":pos, "ROT":rot, "COLOR":client.getClientColor() }
	return location

def receive( ):
	try:
		data, address = client.getClientSocket().recvfrom( 2048 )
		unpickled_data = pickle.loads( data )
		if "PLAYER_UPDATE" in unpickled_data:
			updatePlayerObject( unpickled_data["PLAYER_UPDATE"] )
		elif "PLAYER_SHOOT" in unpickled_data:
			spawnShot( unpickled_data["PLAYER_SHOOT"] )
		elif "TIME_ELAPSED" in unpickled_data:
			timeElapsed( unpickled_data["TIME_ELAPSED"] )
		elif "GAME_STATS" in unpickled_data:
			updateStats( unpickled_data["GAME_STATS"] )
			print( "GAME_STATS")
		elif "END_GAME" in unpickled_data:
			endGame( unpickled_data["END_GAME"] )


	except socket.error:
		pass

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

def spawnShot( data ):
	pos = data["POS"]
	rot = data["ROT"]
	color = data["COLOR"]

	scene = logic.getCurrentScene()
	bullet = scene.addObject( "Bullet", client.getOtherPlayer( color ), 180 )
	bullet["originColor"] = color

	bullet.worldPosition = Vector( pos )
	bullet.worldOrientation = rot

def updatePlayerObject( data ):
	pos = data["POS"]
	rot = data["ROT"]
	color = data["COLOR"]
			
	playerObj = client.getOtherPlayer( color )

	playerObj.worldPosition = Vector( pos )
	playerObj.worldOrientation = rot

	print ( playerObj.worldPosition )

def hit():
	scene = logic.getCurrentScene()
	color = client.getClientColor()

	character = scene.objects["Character"]
	if character["dead"] == True:
		return
	character["dead"] = True

	controller = logic.getCurrentController()
	bullet = controller.owner
	bulletColor = bullet[ "originColor" ]

	spawnNumber = random.randint(1, 5)
	print( spawnNumber )

	spawner = scene.objects[ "SpawnerGame" + color + str( spawnNumber ) ]
	player = scene.objects[ "Character" ]
	player.worldPosition = spawner.worldPosition

	send( { "PLAYER_DEATH": {"DEAD":color, "BANE":bulletColor} } )

def timeElapsed( data ):
	scene = logic.getCurrentScene()
	text = scene.objects["TimeText"]
	text["Text"] = str( data )

def updateStats( data ):
	scene = logic.getCurrentScene()

	character = scene.objects["Character"]
	if character["dead"] == True:
		character["dead"] = False

	text = scene.objects["ScoreText"]
	text["Text"] = str( data )


def endGame( data ):
	pass