import time

from solver.search_stats import SearchStats


class MazeSolver:

    def __init__(
        self,
        maze,
        strategy
    ):
        self.maze = maze
        self.strategy = strategy
        self.observers = []

    def addObserver(
        self,
        observer
    ):
        self.observers.append(
            observer
        )

    def notify(
        self,
        event
    ):
        for observer in self.observers:
            observer.update(event)

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

    def solve(self):

        self.notify(
            "search_started"
        )

        start_time = time.perf_counter()

        path, visited_cells = (
            self.strategy.findPath(
                self.maze,
                self.maze.start,
                self.maze.exit
            )
        )

        finish_time = (
            time.perf_counter()
        )

        elapsed_ms = (
            finish_time
            - start_time
        ) * 1000

        stats = SearchStats(
            elapsed_ms,
            visited_cells,
            len(path)
        )

        self.notify(
            "search_finished"
        )

        return path, stats