from datetime import datetime
from django.utils import timezone
from django.views import generic
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.urls import reverse
import pronostix.models as models
import pronostix.forms as forms

def index(request):
    return render(request, 'pronostix/index.html')
class ProchainesRencontresView(generic.ListView):
    template_name = 'pronostix/prochaines_rencontres.html'
    context_object_name = 'rencontres'
    def get_queryset(self):
        maintenant = datetime.now()
        return models.Rencontre.objects.filter(date__gt=maintenant).order_by('date')
class ResultatsView(generic.ListView):
    template_name = 'pronostix/resultats.html'
    context_object_name = 'resultats'
    def get_queryset(self):
        return models.Resultat.objects.all().order_by('rencontre__date')

@login_required
def lister_pronostics(request):
        liste = []
        now = timezone.now()
        for rencontre in models.Rencontre.objects.filter(date__gt = now).order_by('date'):
            prono = rencontre.pronostic_set.filter(utilisateur = request.user).first()
            liste.append((rencontre, prono))
        return render(request, 'pronostix/pronostics.html', { 'models': liste })

@login_required
def modifier_pronostic(request, rencontre_id):

    prono = get_object_or_404(models.Pronostic, utilisateur = request.user, rencontre_id = rencontre_id)

    if request.method == 'POST':
        form = forms.PronosticForm(request.POST, instance = prono)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('pronostix:pronostics'))
    else:
        form = forms.PronosticForm(instance = prono)

    return render(request, 'pronostix/modifier_pronostic.html', {'prono': form})
    

@login_required
def ajouter_pronostic(request, rencontre_id):

    rencontre = get_object_or_404(models.Rencontre, pk = rencontre_id)

    if request.method == 'POST':
        form = forms.PronosticForm(request.POST)
        if form.is_valid():
            prono = form.save(commit = False)
            prono.utilisateur = request.user
            prono.rencontre = rencontre
            prono.save()
            return HttpResponseRedirect(reverse('pronostix:pronostics'))
    else:
        form = forms.PronosticForm()

    return render(request, 'pronostix/ajouter_pronostic.html', { 'rencontre': rencontre, 'prono': form } )


class HelloView(generic.ListView):
    template_name = 'pronostix/hello.html'
    def get_queryset(self):
        return None
