"""Custom middlewares."""
from django.utils import translation, timezone

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


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)
        request.country_code = country_code

        response = get_response(request)
        return response
    return middleware
