from .models import Jeton
from .views_common import render_common
from django.utils.translation import get_language, activate

def assure_jeton_valide(view_func):
    def wrapped_view(*arg, **kwargs):
        request = arg[0]
        jeton_id = request.session.get("jeton")
        if jeton_id is None:
            jeton_id = request.GET.get("jeton")
            request.session["jeton"] = jeton_id
        jetons = Jeton.objects.filter(id = jeton_id)
        if jetons and jetons[0].estValide():
            result = view_func(*arg, **kwargs)
        else:
            title = "Accès non autorisé"
            if jetons:
                title = "Le jeton est périmé"
            result = render_common(
                request, 'gestion/jeton_perime.html', title,
                {
                    "jeton": jetons[0] if jetons else None,
                },
                pour_tous = True,
            )
        return result
    return wrapped_view

def i18n(view_func):
    def wrapped_view(*arg, **kwargs):
        request = arg[0]
        accept_language = None
        if 'HTTP_ACCEPT_LANGUAGE' in request.META:
            accept_language = request.META['HTTP_ACCEPT_LANGUAGE'].split(",")[0]
        if not request.session.has_key("lang"):
            if accept_language:
                request.session["lang"] = accept_language
            else:
                request.session["lang"] = get_language()
        activate(request.session["lang"])
        return view_func(*arg, **kwargs)
    return wrapped_view

