from typing import Dict, Type

from dependencyinjection import DependencyContext
from httpmessageprocessor import RouterProcessorBuilder, RouteNotMapped
from messageprocessor import MessageProcessor
from simplehttprouter import Route, SimpleHttpRouter


class DiRouterProcessorBuilder(RouterProcessorBuilder):
    def __init__(
        self,
        dependency_context: DependencyContext,
        route_definition: Dict[Route, Type[MessageProcessor]]
    ):
        self.dependency_context = dependency_context
        self.route_definition = route_definition

        self.router = SimpleHttpRouter(list(self.route_definition.keys()))

    def get_processor(self, route):
        found_route = self.router.get_route(route)
        if found_route is None:
            raise RouteNotMapped(route.method, route.path)

        processor_cls = self.route_definition[found_route.route]
        processor_instance = self.dependency_context.get_instance(processor_cls)
        return found_route, processor_instance
