from .models import Jeton
from .views_common import render_common

def assure_jeton_valide(view_func):
    def wrapped_view(*arg, **kwargs):
        request = arg[0]
        jeton_id = request.session.get("jeton")
        print("GRRRR jeton_id = ", 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
