from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView
from django.db.models import Q

from match.models import RefMatch, Points
from joueur.models import Joueur


# Create your views here.
class StatsJoueurList(LoginRequiredMixin, ListView):
    login_url = '/club/login/'
    redirect_field_name = 'redirect_to'
    template_name = 'stats_joueur_list.html'

    def get_queryset(self):
        return Joueur.objects.all().order_by('nom')


@login_required(login_url='../../club/login/')
def stats_list_match(request, pk):
    try:
        joueur = Joueur.objects.get(pk=pk)
        listmatch = RefMatch.objects.filter(joueur_1=joueur).exclude(match_fini=False) | RefMatch.objects.filter(joueur_2=joueur).exclude(match_fini=False)
    except Joueur.DoesNotExist or RefMatch.DoesNotExist:
        return redirect('stats_joueur_list')

    return render(request, 'stats_list_match.html', {'listmatch': listmatch, 'joueur': joueur})


@login_required(login_url='../../club/login/')
def stats_match(request, pkj , pk):
    try: 
        joueur = Joueur.objects.get(pk=pkj)
        refmatch = RefMatch.objects.get(pk=pk)
        listpoint = Points.objects.filter(match=refmatch)
    except RefMatch.DoesNotExist or Points.DoesNotExist:
        return redirect('stats_joueur_list')

    return render (request, 'stats_match.html', {'refmatch': refmatch, 'listpoint': listpoint, 'joueur': joueur})