from Observer import Observer, Event


class ConsoleView(Observer):
    def update(self, event: Event) -> None:
        if event.type == "maze_loaded":
            print("\n[Система] Лабиринт успешно загружен!")
            self.render(event.data.get("maze"))

        elif event.type == "path_found":
            print("\n[Система] Алгоритм нашёл решение!")
            self.render(event.data.get("maze"), path=event.data.get("path"))

        elif event.type == "move":
            print(
                f"\n[Игрок] Переместился в точку: ({event.data.get('player_pos').x}, {event.data.get('player_pos').y})")
            self.render(event.data.get("maze"),
                        player_position=event.data.get("player_pos"))

    def render(self, maze, player_position=None, path=None) -> None:
        path_set = set(path) if path else set()

        for y in range(maze.height):
            row_chars = []
            for x in range(maze.width):
                cell = maze.getCell(x, y)

                if player_position and cell == player_position:
                    row_chars.append("P")
                elif cell.isStart:
                    row_chars.append("S")
                elif cell.isExit:
                    row_chars.append("E")
                elif cell in path_set:
                    row_chars.append(".")
                elif cell.isWall:
                    row_chars.append("#")
                else:
                    row_chars.append(" ")
            print("".join(row_chars))
