import logging

from wevitos.client import _client

logger = logging.getLogger('wevitos')


class WevitosMiddleware:
    """Django middleware that captures unhandled exceptions and reports them to Wevitos."""

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

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exception):
        if _client is None:
            logger.warning('wevitos: middleware active but client not initialized')
            return None

        user_info = None
        if hasattr(request, 'user') and request.user.is_authenticated:
            user_info = {
                'id': request.user.pk,
                'email': getattr(request.user, 'email', ''),
                'username': getattr(request.user, 'username', ''),
            }

        _client.notify(exception, request=request, user=user_info)
        return None
