from django.shortcuts import render
from django.http import FileResponse, Http404, HttpResponse
from django.views.decorators.cache import cache_control
from .models import Plan

# Create your views here.
def horaires_tarifs(request):
    head_title = "Horaires & Tarifs"
    return render(request, 'horaires_tarifs.html', {'head_title': head_title})


def resto_buvettes_foire(request):
    head_title = "Resto et buvettes de la Foire"
    return render(request, 'resto_buvettes_foire.html', {'head_title': head_title})


def espace_gastronomie(request):
    head_title = "L'espace gastronomie"
    return render(request, 'espace_gastronomie.html', {'head_title': head_title})


def qr_code(request):
    head_title = "QR_Code"
    return render(request, 'qr_code.html', {'head_title': head_title})


def serve_pdf(request, plan_id):
    try:
        plan = Plan.objects.get(id=plan_id, actif=True)
        
        # Générer un ETag basé sur la date de modification
        import os
        import time
        file_path = plan.fichier_pdf.path
        file_mtime = os.path.getmtime(file_path)
        etag = f'"{plan_id}-{int(file_mtime)}"'
        
        # Vérifier si le client a déjà la bonne version
        if_none_match = request.META.get('HTTP_IF_NONE_MATCH')
        if if_none_match == etag:
            return HttpResponse(status=304)  # Not Modified
        
        response = FileResponse(plan.fichier_pdf.open('rb'), content_type='application/pdf')
        response['Content-Disposition'] = f'inline; filename="{plan.titre}.pdf"'
        response['X-Content-Type-Options'] = 'nosniff'
        response['ETag'] = etag
        response['Last-Modified'] = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(file_mtime))
        
        # Alternative : désactiver le cache complètement (décommentez si nécessaire)
        # response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        # response['Pragma'] = 'no-cache'
        # response['Expires'] = '0'
        
        return response
    except Plan.DoesNotExist:
        raise Http404("Le plan demandé n'existe pas")

