# -*- coding: utf-8 -*-

from django.utils import translation
from django.db.models import ObjectDoesNotExist
from pybb import util

from pybb.signals import user_saved


class PybbMiddleware(object):
    def process_request(self, request):
        if request.user.is_authenticated():
            try:
                # Here we try to load profile, but can get error
                # if user created during syncdb but profile model
                # under south control. (Like pybb.Profile).
                profile = util.get_pybb_profile(request.user)
            except ObjectDoesNotExist:
                # Ok, we should create new profile for this user
                # and grant permissions for add posts
                user_saved(request.user, created=True)
                profile = util.get_pybb_profile(request.user)

            language = translation.get_language_from_request(request)

            if not profile.language:
                profile.language = language
                profile.save()

            if profile.language and profile.language != language:
                request.session['django_language'] = profile.language
                translation.activate(profile.language)
                request.LANGUAGE_CODE = translation.get_language()

[((24, 23, 24, 69), 'django.utils.translation.get_language_from_request', 'translation.get_language_from_request', ({(24, 61, 24, 68): 'request'}, {}), '(request)', False, 'from django.utils import translation\n'), ((17, 26, 17, 61), 'pybb.util.get_pybb_profile', 'util.get_pybb_profile', ({(17, 48, 17, 60): 'request.user'}, {}), '(request.user)', False, 'from pybb import util\n'), ((32, 16, 32, 54), 'django.utils.translation.activate', 'translation.activate', ({(32, 37, 32, 53): 'profile.language'}, {}), '(profile.language)', False, 'from django.utils import translation\n'), ((33, 40, 33, 66), 'django.utils.translation.get_language', 'translation.get_language', ({}, {}), '()', False, 'from django.utils import translation\n'), ((21, 16, 21, 54), 'pybb.signals.user_saved', 'user_saved', (), '', False, 'from pybb.signals import user_saved\n'), ((22, 26, 22, 61), 'pybb.util.get_pybb_profile', 'util.get_pybb_profile', ({(22, 48, 22, 60): 'request.user'}, {}), '(request.user)', False, 'from pybb import util\n')]