from flask import Response
from flaskmessagehandler import FlaskAdapter, UnhandledEventException, FlaskEventType
from messagebus import Event, SwaggerMessage
from messageprocessor import ApiRequest
from simplehttprouter import HttpRouter, Route


class DefaultFlaskAdapter(FlaskAdapter):
    def __init__(self, router, subject):
        # type: (HttpRouter, str) -> None
        self.subject = subject
        self.router = router

    def get_type(self, path, request):
        if self.router.get_route(Route(request.method, path)) is None:
            raise UnhandledEventException()

        return FlaskEventType.sync_event

    def create_message(self, path, request):
        raise NotImplementedError()

    def create_event(self, path, request):
        route_param = Route(request.method, path)
        route = self.router.get_route(route_param)
        if route is not None:
            return Event(
                self.subject,
                request.method,
                ApiRequest(
                    request.method,
                    route.path,
                    self.router.get_path_parameters(route_param),
                    self.get_query_parameters(request),
                    self.get_headers(request),
                    request.get_data()))

    def get_query_parameters(self, request):
        query_parameters = {}
        if request.args is not None:
            for key in request.args.keys():
                query_parameters[key] = request.args[key]
        return query_parameters

    def get_headers(self, request):
        headers = {}
        if request.headers is not None:
            for key in request.headers.keys():
                headers[key] = request.headers[key]
        return headers

    def create_reply(self, path, request, message):
        if not isinstance(message, SwaggerMessage):
            return Response(status=500, response=b"message was not SwaggerMessage")
        return Response(status=message.status_code, response=message.body, headers=message.headers)
