import pickle
import socket
import _thread
from scripts.multiplayer import game, board, tetriminos

server = "192.168.29.144"
port = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((server, port))
except socket.error as e:
    print(e)

s.listen()
print("Waiting for connection")

connected = set()
games = {}
idCount = 0


def threaded_client(conn, p, gameId):
    global idCount
    conn.send(str.encode(str(p)))

    reply = ""
    while True:
        try:
            data = conn.recv(4096).decode()

            if gameId in games:
                game = games[gameId]

                if not data:
                    break
                else:
                    game.update(p, data)

                    reply = game
                    conn.sendall(pickle.dumps(reply))
            else:
                break
        except:
            break

    print("Lost Connection!")

    try:
        del games[gameId]
        print("Closing Game", gameId)
    except:
        pass
    idCount -= 1
    conn.close()


while True:
    conn, addr = s.accept()
    print("Connected to: ", addr)

    idCount += 1
    p = 0
    game_id = (idCount - 1) // 2

    if idCount % 2 == 1:
        games[game_id] = game.Game((0, 0, 0), None, board)
    else:
        games[game_id].ready = True
        p = 1

    _thread.start_new_thread(threaded_client, (conn, p, game_id))

[((9, 4, 9, 53), 'socket.socket', 'socket.socket', ({(9, 18, 9, 32): 'socket.AF_INET', (9, 34, 9, 52): 'socket.SOCK_STREAM'}, {}), '(socket.AF_INET, socket.SOCK_STREAM)', False, 'import socket\n'), ((73, 4, 73, 65), '_thread.start_new_thread', '_thread.start_new_thread', ({(73, 29, 73, 44): 'threaded_client', (73, 46, 73, 64): '(conn, p, game_id)'}, {}), '(threaded_client, (conn, p, game_id))', False, 'import _thread\n'), ((68, 25, 68, 58), 'scripts.multiplayer.game.Game', 'game.Game', ({(68, 35, 68, 44): '(0, 0, 0)', (68, 46, 68, 50): 'None', (68, 52, 68, 57): 'board'}, {}), '((0, 0, 0), None, board)', False, 'from scripts.multiplayer import game, board, tetriminos\n'), ((39, 20, 39, 40), 'scripts.multiplayer.game.update', 'game.update', ({(39, 32, 39, 33): 'p', (39, 35, 39, 39): 'data'}, {}), '(p, data)', False, 'from scripts.multiplayer import game, board, tetriminos\n'), ((42, 33, 42, 52), 'pickle.dumps', 'pickle.dumps', ({(42, 46, 42, 51): 'reply'}, {}), '(reply)', False, 'import pickle\n')]