return quiz_server


playing = True

IP = input("What is the IP address of the server:\n")
if IP == "":
    IP = "127.0.0.1"

teamName = input("What is your team name?\n")
print("\nWelcome " + teamName)
print("Connecting to Server\n")

quiz_server = connectToServer(IP)

send_binary(quiz_server, ["JOIN", teamName])

while playing:
    for response in get_binary(quiz_server):

        if response[0] == 1:  # Game full
            disconnectFromServer(quiz_server)
            print("The lobby is full, please try again later :(")
            playing = False

        if response[0] == 2:  # Game not full
            print("Connected\n")

        if response[0] == 3:  # Waiting for other players
            print("Waiting for other players. Players connected:\n" +
                  response[1])
    def handle(self):
        global players, answered, current_question, scores
        playing = True
        while playing:
            for command in get_binary(self.request):
                if command[0] == "JOIN":
                    team_name = command[1]
                    scores[team_name] = 0
                    players.append(team_name)
                    print(players[0])
                    if len(players) < MAX_PLAYERS:
                        send_binary(self.request, [1, ""])
                    elif len(players) > MAX_PLAYERS:
                        send_binary(self.request, [2, ""])
                    else:
                        send_binary(self.request, [1, ""])
                        ready_to_start.set()
                    ready_to_start.wait()
                elif command[0] == "STAT":
                    if ready_to_start.isSet() and not wait_for_answers.isSet():
                        send_binary(self.request, [3, "Quiz is starting!"])
                    elif ready_to_start.isSet() and wait_for_answers.isSet():
                        send_binary(self.request, [3, "Quiz Continuing!"])
                elif command[0] == "QUES":
                    if current_question is None:
                        current_question = choice(quiz_questions)
                        wait_for_answers.clear()
                    send_binary(self.request, [4, current_question.q])
                elif command[0] == "ANSW":
                    if command[1].lower() == current_question.answer.lower():
                        scores[team_name] += 1
                        response = 5
                    else:
                        response = 6
                    send_binary(self.request, [response, scores[team_name]])
                    answered += 1
                    if answered == len(players):
                        quiz_questions.remove(current_question)
                        current_question = None
                        wait_for_answers.set()
                    wait_for_answers.wait()

        self.request.send(bytes([8]))
5 - Answer correct
6 - Answer incorrect
7 - Quiz Over
'''

# A flag used to control the quiz loop.
playing = True

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

team_name = input("What is your team name?")

client_socket.connect(("127.0.0.1", 8081))

# Sending a command to the server.
send_binary(client_socket, ["JOIN", team_name])

while playing:
    # The get_binary function returns a list of messages - loop over them
    for response in get_binary(client_socket):
        if response[0] == 1:
            print("Welcome to the quiz team - " + str(team_name))
            send_binary(client_socket, ["STAT", 1])
        elif response[0] == 2:
            print("Access Denied")
            playing = False
        elif response[0] == 3:
            print(response[1])
            send_binary(client_socket, ["QUES", ""])
        elif response[0] == 4:
            print(response[1])
    def handle(self):
        #Retrieve Command
        global teams, answered, current_question, scores
        for command in get_binary(self.request):
            team_name = ""
            if command[0] == "JOIN":
                team_name = command[1]
                if team_name == "":
                    send_binary(self.request, [
                        0, "Team name is manditory. Please enter a valid name"
                    ])
                elif len(team_name) < 3 or len(team_name) > 10:
                    send_binary(self.request, [
                        0,
                        "Team name should be minimum of 3 characters and maximum of 10 characters"
                    ])
                elif team_name in teams:
                    send_binary(self.request,
                                [0, "Team name already taken. Try a new one"])
                else:
                    teams.append(team_name)
                    scores[team_name] = 0
                    lives[team_name] = 3
                    if len(teams) == number_of_teams:
                        send_binary(self.request, [1, ""])
                        ready_to_start.set()
                    elif len(teams) < number_of_teams:
                        send_binary(self.request, [1, ""])
                    elif len(teams) > number_of_teams:
                        send_binary(self.request, [2, ""])
                        teams.pop()

                    ready_to_start.wait()

            elif command[0] == "STAT":
                if len(quiz_questions) == 0:
                    max_score = max(scores, key=scores.get)
                    min_score = min(scores, key=scores.get)
                    if min_score == max_score:
                        send_binary(self.request, (8, "It's a tie"))
                    else:
                        winners = []
                        for score in scores:
                            if max_score == score:
                                winners.append(score)
                        if len(winners) == 1:
                            send_binary(
                                self.request,
                                (8, f"Team {winners[0].upper()} won the quiz"))
                        else:
                            send_binary(self.request, (
                                8,
                                f"Teams {','.join(winners).upper()} won the quiz"
                            ))
                    continue
                if ready_to_start.isSet() and not wait_for_answers.isSet():
                    send_binary(self.request, [3, "Quiz is starting!"])
                elif ready_to_start.isSet() and wait_for_answers.isSet():
                    if len(teams) == 1:
                        send_binary(self.request, (
                            8,
                            "Congrats you have won the quiz, all of your opponents have been eliminated"
                        ))
                    else:
                        send_binary(self.request,
                                    [3, "Your next question......"])

            elif command[0] == "QUES":
                if len(teams) == 1:
                    send_binary(self.request, (
                        8,
                        "Congrats you have won the quiz, all of your opponents have been eliminated"
                    ))
                else:
                    if current_question == None:
                        current_question = choice(quiz_questions)
                        wait_for_answers.clear()

                    send_binary(
                        self.request,
                        (4, [current_question.q, current_question.options]))

            elif command[0] == "ANSW":
                if command[1].lower() == current_question.answer.lower():
                    scores[team_name] += 1
                    if len(teams) == 1:
                        send_binary(self.request, (
                            8,
                            "Congrats you have won the quiz, all of your opponents have been eliminated"
                        ))
                    else:
                        response = 5
                        send_binary(self.request,
                                    [response, scores[team_name]])
                else:
                    lives[team_name] -= 1
                    if lives[team_name] == 0:
                        teams.remove(team_name)
                        answered -= 1
                        response = 8
                        send_binary(self.request,
                                    (response, "You lost. Out of lives"))
                    else:
                        response = 6
                        send_binary(self.request, [response, lives[team_name]])
                answered += 1
                if answered == len(teams):
                    quiz_questions.remove(current_question)
                    current_question = None
                    answered = 0
                    wait_for_answers.set()

                wait_for_answers.wait()