import pygame
from map import Map
from waiter import Waiter
from order_screen import OrderScreen
from stadistics import Stadistics
from scripts.remake_database import remake_database


algorithm_choices = ["least-loaded", "round-robin", "power-of-two-choices", "custom-1", "custom-2"]
def print_algorithm_choices():
    # Imprimir las opciones de algoritmo disponibles numerados
    print("Elige un algoritmo de asignación de órdenes:")
    for i, alg in enumerate(algorithm_choices):
        print(f"{i + 1}. {alg}")

class Main:
    def __init__(self, width=16*50, height=16*50):
        pygame.init()
        resp = input("¿Quieres rehacer la base de datos? (s/n): ").strip().lower()
        print_algorithm_choices()
        choice = input("Introduce el número del algoritmo deseado: ").strip()
        try:
            choice_index = int(choice) - 1
            if 0 <= choice_index < len(algorithm_choices):
                self.algorithm = algorithm_choices[choice_index]
            else:
                print("Número inválido, se usará el algoritmo por defecto 'least-loaded'.")
                self.algorithm = "least-loaded"
        except ValueError:
            print("Entrada inválida, se usará el algoritmo por defecto 'least-loaded'.")
            self.algorithm = "least-loaded"

        self.speed = 15
        if resp == 's' or resp == 'si' or resp == 'y':
            remake_database(self.algorithm)
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption('Pantalla en blanco')
        self.clock = pygame.time.Clock()
        self.running = True
        self.map = Map('map.json')
        self.map_editing = False
        self.order_screen = OrderScreen(self.screen, self.speed)
        start_pos = (25, 43)  # misma posición inicial para todos
        waiter_names = ["Jan", "Pol", "Martina", "Sandra", "Dani", "Aladid", "Ivet"]
        self.fps = 60
        self.waiters = [
            Waiter(waiter_names[i], self.order_screen.data, start_pos, self.speed, offset=(i-3)) for i in range(len(waiter_names))
        ] 
        self.stadistics = Stadistics(self.screen, self.waiters)

    def run(self):
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if self.map_editing:
                            self.map.left_click(event.pos)
                    elif event.button == 3:
                        if self.map_editing:
                            self.map.right_click(event.pos)
                    elif event.button == 4:
                        if self.map_editing:
                            self.map.scroll_up(event.pos)
                    elif event.button == 5:
                        if self.map_editing:
                            self.map.scroll_down(event.pos)
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_c:
                        self.map.on_c_pressed()
                    if event.key == pygame.K_m:
                        self.map_editing = not self.map_editing

            self.screen.fill((255, 255, 255))  # Blanco
            self.map.update()
            self.map.drawMap(self.screen)
            self.order_screen.draw()
            self.stadistics.draw_waiter_loads((3*16, 4*16))
            self.stadistics.draw_waiter_waiting_times((18*16, 4*16))
            self.stadistics.draw_avg_order_prep_time(self.order_screen.data,(33*16, 4*16))

            # actualizar y dibujar todos los camareros
            for waiter in self.waiters:
                waiter.update(self.map)
                waiter.draw(self.screen)

            pygame.display.flip()
            self.clock.tick(self.fps)
        pygame.quit()

if __name__ == '__main__':
    app = Main()
    app.run()
