'''
Created on 19 maj 2014

@author: Reii
'''

import constants
import socket
import pickle
import time

class ServerGame: 

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

    def initScoreBoard( self ):
        self.scoreBoard = {}
        for address in self.users:
            user = self.users[ address ]
            self.scoreBoard[ user.color[0] ] = 0
            
        
    def run( self ):
        
        self.initClients()
        
        self.startTime =  time.clock()
        self.timeElapsed = time.clock() - self.startTime
        lastTimeTick = time.clock()
        gameStatSent = False
        while self.server.running and not self.timeElapsed > 60 * self.server.gameTime:
            self.receive()
            self.timeElapsed = time.clock() - self.startTime
            if time.clock() - lastTimeTick > 1:
                self.sendTimeElapsed( )
                lastTimeTick = time.clock()
                if not gameStatSent:
                    self.sendGameStats( )
                    gameStatSent = True
           
        self.server.send( { constants.MSG_END_GAME:self.scoreBoard } )
    
    def receive( self ):
        try: 
            data, address = self.socket.recvfrom( 1024 )
            
            unpickled_data = pickle.loads( data )

            if constants.MSG_PLAYER_UPDATE in unpickled_data:
                self.playerUpdated( unpickled_data, address )

            elif constants.MSG_PLAYER_DEATH in unpickled_data:
                self.playerDied( unpickled_data )
                
            elif constants.MSG_PLAYER_SHOOT in unpickled_data:
                self.playerShoot( unpickled_data, address )

        except socket.error:
            return
    
    def initClients( self ):
        playerColors = []
        for address in self.users:
            player = self.users[address]
            playerColors.append( player.color[0] )
        
        msg = { constants.MSG_START_GAME:playerColors }
        self.server.send( msg )
    
    def playerUpdated( self, data, address ):
        self.server.sendExclude( data, address )
        
    def playerShoot( self, data, address ):
        self.server.sendExclude( data, address )
        
    def playerDied( self, data ):
        print "player died "+ str(data) 
        data = data[ constants.MSG_PLAYER_DEATH ]
        
        dead = data[ constants.MSG_PLAYER_DEAD ]
        bane = data[ constants.MSG_PLAYER_BANE ]
        
        if bane != None:
            prev = self.scoreBoard[ bane ]
            self.scoreBoard[ bane ] = prev + 1
        else:
            prev = self.scoreBoard[ dead ]
            self.scoreBoard[ dead ] = prev - 1
            
        self.sendGameStats( )
    
    def sendTimeElapsed( self ):
        secondsElapsed = int( self.timeElapsed )
        minsElapsed = int( secondsElapsed / 60 ) 
        secondsElapsed = secondsElapsed - minsElapsed * 60 
        timeElapsed = "Time elapsed: " + str( minsElapsed ) + " min " + str( secondsElapsed ) + " sec"
        
        self.server.send( { constants.MSG_TIME_ELAPSED:timeElapsed } )
        
    def sendGameStats( self ):        
        statStr = ""
        
        for address in self.users:
            user = self.users[ address ]
            score = self.scoreBoard[ user.color[0] ]
            statStr = statStr + str( user.name ) + ": " + str( score ) + "\n" 
            
        self.server.send( { constants.MSG_GAME_STATS:statStr } )
            