# coding: utf-8

import logging
from contextlib import wraps
from time import perf_counter

from ylog.context import log_context

from procu.api.utils import get_current_url

logger = logging.getLogger('access_log')


def timed_access_logger(view_func):
    @wraps(view_func)
    def wrapped(request, *args, **kwargs):

        started_at = perf_counter()
        response = view_func(request, *args, **kwargs)

        request_time = int((perf_counter() - started_at) * 1000000.0)

        final_context = {
            'view': f'{view_func.__module__}.{view_func.__name__}',
            'request_time': request_time,
            'response': {'status': response.status_code},
        }

        # query_logger = getattr(request, 'query_logger')
        # if query_logger is not None:
        #     final_context['queries'] = query_logger.queries or None

        with log_context(**final_context):
            logger.info(
                '%s %s => %s',
                request.method,
                get_current_url(request),
                response.status_code,
            )

        return response

    return wrapped
