import uuid

from ylog import context

from django.utils.deprecation import MiddlewareMixin

from .settings import REQUEST_ID_HEADER


class LogUidMiddleware(MiddlewareMixin):
    def process_request(self, request):
        yauid = getattr(request.user, 'yauid', None)
        if yauid:
            context.put_to_context('yauid', yauid)

    def process_response(self, request, response):
        context.pop_from_context('yauid')
        return response


class LogRequestIdMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request_id = request.META.get(REQUEST_ID_HEADER, '') or uuid.uuid4().hex
        context.put_to_context('request_id', request_id)

    def process_response(self, request, response):
        context.pop_from_context('request_id')
        return response
