"""Custom middlewares."""
import logging

from django.utils import translation, timezone
from django.db import connection

from account.models import User
from configuration.models import TranslationSettings
from main.methods import determine_user_city
from main.models import SiteSettings
from translation.models import Language

logger = logging.getLogger(__name__)


def get_locale(cookie_dict):
    return cookie_dict.get('locale')


def get_country_code(cookie_dict):
    return cookie_dict.get('country_code')


def user_last_visit(get_response):
    """Updates user last visit w/ current"""

    def middleware(request):
        response = get_response(request)
        if request.user.is_authenticated:
            User.objects.filter(pk=request.user.pk).update(**{
                'last_login': timezone.now(),
                'locale': request.locale,
                'city': determine_user_city(request),
            })
        return response

    return middleware


def parse_cookies(get_response):
    """Parse cookies."""

    def middleware(request):
        cookie_dict = request.COOKIES
        # processing locale cookie
        locale = get_locale(cookie_dict)
        # todo: don't use DB!!! Use cache
        if not Language.objects.filter(locale=locale).exists():
            locale = TranslationSettings.get_solo().default_language
        translation.activate(locale)
        request.locale = locale

        # processing country country cookie
        country_code = get_country_code(cookie_dict)
        if country_code and country_code != 'None':
            request.country_code = country_code
        else:
            request.country_code = None

        response = get_response(request)
        return response

    return middleware


def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def user_last_ip(get_response):
    """Update user last ip address and last country"""

    def middleware(request):
        response = get_response(request)
        current_ip = get_client_ip(request)

        country_code = request.COOKIES.get('country_code')
        current_site = SiteSettings.objects.by_country_code(country_code).first()
        if not current_site:
            current_site = SiteSettings.objects.filter(subdomain='www').first()

        if request.user.is_authenticated:

            payload = {}
            if request.user.last_ip != current_ip:
                payload.update({
                    'last_ip': current_ip,
                })
            if request.user.last_country != current_site:
                payload.update({
                    'last_country': current_site,
                })
            if payload:
                User.objects.filter(pk=request.user.pk).update(**payload)
        return response

    return middleware


def log_db_queries_per_API_request(get_response):
    """Middleware-helper to optimize requests performance"""

    def middleware(request):
        total_time = 0
        response = get_response(request)
        for query in connection.queries:
            query_time = query.get('time')
            if query_time is None:
                query_time = query.get('duration', 0) / 1000
            total_time += float(query_time)

        total_queries = len(connection.queries)
        if total_queries > 10:
            logger.error(
                f'\t{len(connection.queries)} queries run, total {total_time} seconds \t'
                f'URL: "{request.method} {request.get_full_path_info()}"'
            )
        return response

    return middleware
