import os


from .observer import Observer, Event
from source.classes import Cell, Maze

class ConsoleView(Observer):

    def update(self, event: Event):
        """Вывод состояния лабиринта на экран
        
        `maze_loaded` - Лабиринт загружен

        `path_found` - Отображает лабиринт и маршрут в нём (символом `*`)

        `move` - Выводит лабиринт и позицию игрока в нём (символом `P`)
        
        """
        if event.event == "path_found":
            print("Путь найден:")
            self.render(
                event.maze,         
                event.player_position, 
                event.path
                )
        elif event.event == "move":
            self.render(
                event.maze,         
                event.player_position, 
                event.path
                )
        elif event.event == "maze_loaded":
            print("Загружен лабиринт:")
            self.render(
                event.maze,         
                event.player_position, 
                event.path
                )
        else:
            pass
        

    def render(self, maze:Maze, player_position: tuple[int, int], path: list):
        os.system('cls' if os.name == 'nt' else 'clear')

        # Если path содержит объекты Cell, преобразуем в координаты
        if path and isinstance(path[0], Cell):
            path_xy = [cell.getXY() for cell in path]
        else:
            path_xy = path

        # path_xy = [cell.getXY() for cell in path]
        
        for line in maze.cells:
            for c in line:
                if c.getXY() == player_position:
                    print('P', end='')
                elif c.toStr() in ["S", "E"]:
                    print(c.toStr(), end='')
                elif c.getXY() in path_xy:
                    print('.', end='')
                else:
                    print(c.toStr(), end='')

            print()

    # def render_xy(self, maze: Maze, player_position: tuple[int, int], path: list[tuple[int, int]]):
    #     os.system('cls' if os.name == 'nt' else 'clear')
    #     # path_xy = [cell.getXY() for cell in path]
        
    #     for line in maze.cells:
    #         for c in line:
    #             if c.getXY() == player_position:
    #                 print('P', end='')
    #             elif c.getXY() in path:
    #                 print('*', end='')
    #             else:
    #                 print(c.toStr(), end='')
    #         print()