"""Contains middleware for easy Django integration"""
import gtransport
from gtransport.constants import TRACE_ID_HEADER_NAME


class DjangoMiddleware(object):
    """
    Old middleware. Before middleware interface was changed.
    """

    def __init__(self):
        # One-time configuration and initialization.
        from django.conf import settings as django_settings
        self.service_name = (getattr(django_settings, 'GTRANSPORT_APP', None)
                             or 'default_svc')
        gtransport.configure(
            strict=True,
            headers={'service': self.service_name}
        )

    def process_request(self, request):
        """
        @param request: django.http.request, a Django request object
        @return:
        """
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        gtransport.bind_transport_client(
            headers={
                TRACE_ID_HEADER_NAME: request.gr_trace_id
            }
        )

    def process_response(self, request, response):
        """
        @param request: django.http.request, a Django request object
        @param response: django.http.response, a Django response object
        @return:
        """
        # Code to be executed for each request/response after
        # the view is called.
        return response

    def process_exception(self, request, exception):
        """

        @param request:
        @param exception:
        @return:
        """
        pass


class DjangoMiddlewareNew(object):
    """
    Middleware for latest Django
    """

    def __init__(self, get_response):
        """
        @param get_response: callable, the callback, that shall be
        invoked by this middleware to propogate the request further
        in the application
        """
        # One-time configuration and initialization.
        self.get_response = get_response
        from django.conf import settings as django_settings
        self.service_name = (getattr(django_settings, 'GTRANSPORT_APP', None)
                             or 'python')
        gtransport.configure(
            strict=True,
            headers={'service': self.service_name}
        )

    def __call__(self, request):
        """
        Invokes this middleware, attaching a trace id to gtransport.
        Any http request originating from gtransport will have this
        trace id.
        @param request: django.http.request, a Django request object
        @return:
        """
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        gtransport.bind_transport_client(
            headers={
                TRACE_ID_HEADER_NAME: request.gr_trace_id
            }
        )
        response = self.get_response(request)
        # Code to be executed for each request/response after
        # the view is called.
        return response
