'''
Created on 19 maj 2014

@author: Reii
'''

from threading import Thread
import socket
import serverLobby
import serverGame
import utils
import pickle

class Server: 

    def __init__( self, port, maxPlayers, gameTime, gui, host = "localhost" ):

        self.socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
        self.socket.setblocking( False )
        self.socket.bind( ( host, port ) )

        self.address_to_user = {}
        self.availableColors = self.generateAvailableColors( maxPlayers )
        self.maxPlayers = maxPlayers
        self.gameTime = gameTime
        
        self.gui = gui

    def openLobby( self ):
        self.lobby = serverLobby.ServerLobby( self )
        self.running = True
        Thread( target=self.lobby.run ).start()

    def openGame( self ):
        self.game = serverGame.ServerGame( self )
        Thread( target=self.game.run ).start()

    def generateAvailableColors( self, maxPlayers ):
        colors = utils.availableColors
        available = {}
        for x in range( 0, maxPlayers ):
            available[ colors.keys()[x] ] = colors.values()[x]
        return available
    
    def send( self, data ):
        pickled_data = pickle.dumps( data )
        for address in self.address_to_user:
            self.socket.sendto( pickled_data, address )
                
    def sendTo( self, data, address ):
        pickled_data = pickle.dumps( data )
        self.socket.sendto( pickled_data, address )
        
    def sendExclude( self, data, address ):
        pickled_data = pickle.dumps( data )
        for addr in self.address_to_user:
            if addr != address:
                self.socket.sendto( pickled_data, addr )

class Player: 

    def __init__( self, name, color ):
        self.name = name
        self.color = color
        self.ready = False

