import re
from django.http import HttpResponse
from django_yauth.middleware import YandexAuthBackendMiddleware


def PingMiddleware(get_response):
    ping_re = re.compile(r'^/ping/?$')

    def middleware(request):
        if ping_re.match(request.path):
            return HttpResponse('OK')

        response = get_response(request)
        return response
    return middleware


try:
    import uwsgi
except ImportError:
    uwsgi = None


import logging
logger = logging.getLogger(__name__)


def UwsgiLogMiddleware(get_response):

    USER_IP_HEADERS = (
        'HTTP_X_REAL_IP',
        'HTTP_X_FORWARDED_FOR',
        'REMOTE_ADDR',
    )

    HOST_HEADERS = (
        'HTTP_X_FORWARDED_HOST',
        'HTTP_HOST',
    )

    def extract_actual_header(request, headers):
        for header_name in headers:
            ip = request.META.get(header_name)
            if ip:
                return ip
        return None

    def middleware(request):

        if not uwsgi:
            return get_response(request)

        try:
            yandex_login = request.COOKIES.get('yandex_login')
            if yandex_login:
                uwsgi.set_logvar('yandex_login', yandex_login)

            user_ip = extract_actual_header(request, USER_IP_HEADERS)
            if user_ip:
                uwsgi.set_logvar('user_ip', user_ip)

            host = extract_actual_header(request, HOST_HEADERS)
            if host:
                uwsgi.set_logvar('real_host', host)
        except Exception:
            logger.exception('Exception on set uWSGI logvar')

        response = get_response(request)

        try:
            if request.resolver_match:
                uwsgi.set_logvar('view_name', request.resolver_match.view_name)
            else:
                uwsgi.set_logvar('view_name', '?')
            # client_application = getattr(request, 'client_application', None)
            # if client_application:
            #     uwsgi.set_logvar('client_application', client_application.name.encode('utf-8'))
            #     uwsgi.set_logvar('client_id', client_application.id)
            user = getattr(request, 'user', None)
            if user:
                uwsgi.set_logvar('yandex_login', user.username)

        except Exception:
            logger.exception('Exception on set uWSGI logvar')

        return response
    return middleware


class AuthMiddleware(YandexAuthBackendMiddleware):
    def process_request(self, request):
        super().process_request(request)

        if request.yauser is None or not request.yauser.is_authenticated():
            return HttpResponse(status=401)
