import time

from observer.subject import Subject
from observer.maze_event import MazeEvent, MazeEventType
from models.search_stats import SearchStats


class MazeSolver(Subject):

    def __init__(self, maze, strategy):
        super().__init__()
        self.maze = maze
        self.strategy = strategy

    def set_strategy(self, strategy):
        self.strategy = strategy

    def solve(self):

        start_time = time.perf_counter()

        path, visited = self.strategy.find_path(
            self.maze,
            self.maze.start_cell,
            self.maze.exit_cell
        )

        end_time = time.perf_counter()

        self.notify(
            MazeEvent(
                MazeEventType.PATH_FOUND,
                path
            )
        )

        return SearchStats(
            strategy=self.strategy.__class__.__name__,
            maze_name="maze",
            duration=(end_time - start_time) * 1000,
            visited_cells=visited,
            path_length=len(path)
        )