from httpmessageprocessorutil.automapped import exec_map
from messageprocessor import MessageProcessorCallback

from edpauthorization.exception import NotAuthorizedException
from edpauthorization.registry import check_registry_authorized, cleanup_authz_registry


@exec_map({"status_code": 403, "body": "Forbidden"})
class HttpAuthorizationError(NotAuthorizedException):
    ...


class AuthorizationCallback(MessageProcessorCallback):
    def input_parsed(self, event_name, request_id, input_obj):
        try:
            check_registry_authorized()
        except NotAuthorizedException as e:
            raise HttpAuthorizationError(str(e)) from e

    def process_begun(self, event_name, request_id, **kwargs):
        ...

    def business_called(self, event_name, request_id, input_obj, output_obj):
        ...

    def process_finished(self, event_name, request_id, input_obj, output_obj):
        cleanup_authz_registry()

    def parse_exception(self, event_name, request_id, data, exception):
        cleanup_authz_registry()

    def unhandled_exception(self, event_name, request_id, input_obj, exception):
        cleanup_authz_registry()
