import logging

import glogger


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

    def __init__(self):
        from django.conf import settings as django_settings
        glogger.configure(
            app=getattr(django_settings, 'GLOGGER_APP', None) or 'python',
            env=getattr(django_settings, 'GLOGGER_ENV', None) or 'dev',
            level=getattr(django_settings, 'GLOGGER_LEVEL', None) or logging.INFO
        )

    def process_request(self, request):
        glogger.new_logger(request=request)
        request.gr_trace_id = glogger.get_trace_id()

    def process_response(self, request, response):
        # log response too?
        if not response.has_header('X-Gr-Trace-Id'):
            response['X-Gr-Trace-Id'] = glogger.get_trace_id()
        return response

    def process_exception(self, request, exception):
        # log response too?
        pass


class DjangoMiddlewareNew:
    """
    Middleware for latest Django
    """

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

        from django.conf import settings as django_settings
        glogger.configure(
            app=getattr(django_settings, 'GLOGGER_APP', None) or 'python',
            env=getattr(django_settings, 'GLOGGER_ENV', None) or 'dev',
            level=getattr(django_settings, 'GLOGGER_LEVEL', None) or logging.INFO
        )
        # One-time configuration and initialization.

    def __call__(self, request):
        glogger.new_logger(request=request)
        request.gr_trace_id = glogger.get_trace_id()
        response = self.get_response(request)
        return response
