import time

from Client.Client import Client, MAX_DISTANCE, glutPostRedisplay
from MatrixStuff.Transformations import perspectiveMatrix
from labirinth_ai.LabyrinthProvider import LabyrinthProvider

import numpy as np


class LabyrinthClient(Client):
    def __init__(self, test=False, pos=[0, 0, 0], world_class=LabyrinthProvider):
        self.render = True
        self.round_timer = time.time()
        super(LabyrinthClient, self).__init__(test, pos, world_class)

    def draw_world(self):
        start_time = time.time()
        for x in range(self.world_provider.world.chunk_size_x * self.world_provider.world.chunk_n_x):
            for y in range(self.world_provider.world.chunk_size_y * self.world_provider.world.chunk_n_y):
                if self.world_provider.world.board[x, y] in [1, 2]:
                    r, g, b = 57, 92, 152
                    if 1.5 >= self.world_provider.world.hunter_grass[x, y] > 0.5:
                        r, g, b = 112, 198, 169
                    if 3 >= self.world_provider.world.hunter_grass[x, y] > 1.5:
                        r, g, b = 25, 149, 156
                    self.world_provider.world.set_color(x, y, 0, r / 255.0, g / 255.0, b / 255.0)
                if self.world_provider.world.board[x, y] == 3:
                    self.world_provider.world.set_color(x, y, 0, 139 / 255.0, 72 / 255.0, 82 / 255.0)

        for sub in self.world_provider.world.subjects:
            if not sub.random:
                # pyxel.rectb(sub.x * 4 + 1, sub.y * 4 + 1, 2, 2, sub.col)
                self.world_provider.world.set_color(sub.x, sub.y, 0, sub.r / 255.0, sub.g / 255.0, sub.b / 255.0)
            else:
                self.world_provider.world.set_color(sub.x, sub.y, 0, 212 / 255.0, 150 / 255.0, 222 / 255.0)

        self.projMatrix = perspectiveMatrix(45.0, 400 / 400, 0.01, MAX_DISTANCE)
        # print('redraw', time.time() - start_time)

    def display(self):
        if self.render:
            super(LabyrinthClient, self).display()
            self.draw_world()
        else:
            glutPostRedisplay()
        self.world_provider.world.update()
        # round_end = time.time()
        # print('round time', round_end - self.round_timer)
        # self.round_timer = round_end

    def keyboardHandler(self, key: int, x: int, y: int):
        super().keyboardHandler(key, x, y)

        if key == b' ':
            self.render = not self.render


if __name__ == '__main__':
    client = LabyrinthClient(pos=[-50, -50, -200])