from flask import Flask, render_template, request, session, make_response
import socket
import time
import numpy as np
from playsound import playsound
from itertools import zip_longest
import random
import json
import pygame

app = Flask(__name__)
app.secret_key = b'RoboRallyRolling'

probabilities = [0.21428571428571427, 0.14285714285714285, 0.07142857142857142, 0.07142857142857142,
                 0.21428571428571427, 0.21428571428571427, 0.07142857142857142]

#deck = roborally.CardDeck()

class Cmd:
    possible_moves = ['forward', 'left', 'right', 'P0']
    possible_colors = [(200,200,200), (255, 0, 0), (0,0,255)]

    def __init__(self, action, color):
        self.action = action
        self.color = color

    def __str__(self):
        return "Cmd No. " + self.action

    def __repr__(self):
        return self.action + " " + str(self.color)


available_robots = {
    0: {'id': 11, 'ip': '192.168.1.11', 'x': 1, 'y': 2, 'orientation': '>'},
    1: {'id': 12, 'ip': '192.168.1.12', 'x': 3, 'y': 3, 'orientation': '>'}
}


players = {}


class Player:
    MAX_PLAYERS = 4
    player_counter = 0

    def __init__(self):
        if Player.player_counter < Player.MAX_PLAYERS:
            self.id = Player.player_counter
            Player.player_counter += 1

            self.max_cards = 9

            self.player_hand = deck.draw_cards(self.max_cards)
            print("current hand: ", [str(c) for c in self.player_hand])

            self.action_count = 5
            self.action_chosen = False

            self.initialize_robot()

        else:
            print("max players reached!")

    def initialize_robot(self):
        x = available_robots[self.id]['x']
        y = available_robots[self.id]['y']
        marker_id = available_robots[self.id]['id']
        ip = available_robots[self.id]['ip']
        orientation = available_robots[self.id]['orientation']
        self.robot = game.board.create_robot(x, y, orientation, self.id, marker_id)

        if game.comm_socket is not None:
            cmd = f"initialize_robot, {marker_id}, {ip}, {x-1}, {y-1}, {orientation}\n"
            game.comm_socket.sendall(cmd.encode())
            data = game.comm_socket.recv(32)

            if data.decode() == 'OK\n':
                print("robot sucessfully initialized!")
            else:
                print("error: could not initialize robot!")
                self.robot = None

    def draw_new_cards(self):
        self.player_hand += deck.draw_cards(self.max_cards - len(self.player_hand))


@app.route('/send_cmds', methods=['POST', 'GET'])
def send_cmds():
    if request.method == 'POST':
        cmds = json.loads(request.form['cmds_json'])

        cmd_list = []
        for cmd_nr in [f"cmd{i}" for i in range(5)]:
            cmd = cmds[cmd_nr]
            action = cmd['action']
            color_str = cmd['color']
            color_str = color_str.strip("()").split(",")
            color = tuple(map(int, color_str))
            cmd_list.append(Cmd(action, color))
        print("got commands: ", cmd_list)
        ev = pygame.event.Event(pygame.USEREVENT, {'cmds': cmd_list})
        pygame.event.post(ev)

        # send commands to the game

        # if game.ready():
        #     game.process_actions()
        #
        #     return 'OK'
        # else:
        #     return 'please wait'
        return "OK"
    elif request.method == 'GET':
        # GET is used when we have to wait for other players to finish
        while not game.processing_done:  # wait for other players to choose commands and processing to finish
            pass

        return 'OK'

WHITE = (255, 255, 255)
GRAY = (200, 200, 200)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    prg = [Cmd('forward', GRAY), Cmd('left', GRAY), Cmd('right', BLUE),
                   Cmd('P0', GRAY), Cmd('right', RED)]
    valid_cmds = [Cmd('forward', WHITE), Cmd('right', WHITE), Cmd('left', WHITE),
                  Cmd('P0', WHITE), Cmd('-', RED), Cmd('-', BLUE), Cmd('-', GRAY)]

    if request.method == 'GET':
        robot_info = None
        return render_template('drag_example.html', current_program=prg, valid_commands=valid_cmds, robot_info=robot_info)
    elif request.method == 'POST':
        # print(request.form)

        if request.form.get('drag') and request.form.get('drop'):
            # swap cards in the current hand
            i1 = int(request.form.get('drag'))  # number of first card
            i2 = int(request.form.get('drop'))  # number of second card

            card1 = deck.deck[i1]  # get card by number
            card2 = deck.deck[i2]

            print("swapping {} and {}".format(card1, card2))

            j1 = player_hand.index(card1)  # get index of card in the hand
            j2 = player_hand.index(card2)

            player_hand[j1], player_hand[j2] = player_hand[j2], player_hand[j1]  # swap the cards in the list

            # print("current hand: ", [str(c) for c in player_hand[player_id]])

            return 'OK'
        else:
            return render_template('drag_example.html', cmds=player_hand, player_id=player_id)


if __name__ == '__main__':
    #app.run(host='192.168.1.222', port=5000)
    app.run(host='0.0.0.0', port=5000)
