import time

from functools import wraps
from django.core.handlers.wsgi import WSGIHandler

import logging
logger = logging.getLogger(__name__)


def time_mwm(mwm):
    @wraps(mwm)
    def inner(request, *args, **kwargs):

        t1 = time.time()
        result = mwm(request, *args, **kwargs)
        t2 = time.time()
        delta = int(round((t2-t1) * 1000))
        if delta > 5:
            req_id = request.META.get('HTTP_X_REQ_ID', '')
            logger.debug(
                '%s.%s %sms %s',
                mwm.__self__.__class__.__name__,
                mwm.__func__.__name__,
                str(delta),
                req_id
            )
        return result

    return inner


class StaffWSGIHandler(WSGIHandler):
    def load_middleware(self):
        super(StaffWSGIHandler, self).load_middleware()

        mwm_lists = (
            '_view_middleware',
            '_template_response_middleware',
            '_response_middleware',
            '_exception_middleware',
            '_request_middleware',
        )

        for mwv_list in mwm_lists:
            setattr(self, mwv_list, [time_mwm(mwm) for mwm in getattr(self, mwv_list)])

    def get_response(self, request):
        result = time_mwm(super(StaffWSGIHandler, self).get_response)(request)
        return result
