from django.http import HttpResponse


try:
    from django.utils.deprecation import MiddlewareMixin

    MiddlewareClass = MiddlewareMixin
except ImportError:
    MiddlewareClass = object


class CatchExceptionMiddleware(MiddlewareClass):
    def process_exception(self, request, exception):
        return HttpResponse(status=500)


class HandleErrorMiddlewareSuccess(MiddlewareClass):
    def process_exception(self, request, exception):
        return HttpResponse(status=200)


class HandleErrorMiddlewareClientError(MiddlewareClass):
    """Converts an HttpError (that may be returned from an exception handler)
    generated by a view or previous middleware and returns a 404
    HttpResponse.
    """

    def process_response(self, request, response):
        if response.status_code == 500:
            return HttpResponse(status=404)

        return response


def fn_middleware(get_response):
    """Function factory middleware."""

    def mw(request):
        response = get_response(request)
        return response

    return mw


def fn2_middleware(get_response):
    """Function factory middleware."""

    def mw(request):
        response = get_response(request)
        return response

    return mw


def empty_middleware(get_response):
    """Empty function middleware for regression testing."""

    def mw(request):
        pass

    pass


class ClsMiddleware:
    """Class middleware."""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response


class EverythingMiddleware:
    """Middleware using all possible middleware hooks."""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    def process_response(self, req, resp):
        return resp

    def process_request(self, req):
        return req

    def process_exception(self, request, exception):
        pass

    def process_view(self, request, view_func, view_args, view_kwargs):
        pass

    def process_template_response(self, req, resp):
        return resp
