from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.views.generic.edit import CreateView, DeleteView
from django.views.generic import ListView
from django.views import generic
from .models import RefMatch, Points, ChoixJoueur
from match.forms import PointsForm, UpdateForm, MatchCreateForm, MatchDeleteForm, ChoixJoueurForm
from classement.models import DistCat
from club.models import Club
from django.contrib.auth.models import User

'''
class MatchCreate(LoginRequiredMixin, CreateView):
    login_url = '/club/login/'
    redirect_field_name = 'redirect_to'
    model = RefMatch

    fields = ['date', 'lieu', 'mode_jeu', 'categorie', 'distance',
              'joueur_1', 'joueur_2', 'arbitre', 'type_match', ]
    template_name = 'form_match.html'
'''


class MatchCreate(LoginRequiredMixin, CreateView):
    login_url = '/club/login/'
    redirect_field_name = 'redirect_to'
    model = RefMatch
    fields = ['date', 'mode_jeu', 'categorie', 'distance',
              'joueur_1', 'joueur_2', 'arbitre', 'type_match']
    template_name = 'form_match.html'

    def get_sucess_url(self):
        return reverse('list_match')

    def form_valid(self, form):
        form.instance.lieu_organisation = self.request.user
        return super().form_valid(form)

# les vues de détail de l'arbitrage des matchs sur ordinateur et sur portable ont été séparé
# car la vue d'arbitrage sur ordinateur nécessite un rafraichissement automatique qui n'est pas souhaitable
# d'avoir aussi sur la vue sur portable pour un gain de ressource serveur

class MatchList(LoginRequiredMixin, ListView):
    login_url = '/club/login/'
    redirect_field_name = 'redirect_to'
    template_name = 'listmatch.html'

    def get_queryset(self):
        utilisateur = self.request.user
        # Retourne seulement les matchs non joués du club authentifié
        return RefMatch.objects.all().exclude(match_fini=True).filter(lieu_organisation=utilisateur)


class MatchListUpdel(LoginRequiredMixin, ListView):
    login_url = '/club/login/'
    redirect_field_name = 'redirect_to'
    template_name = 'listmatchupdel.html'

    def get_queryset(self):
        utilisateur = self.request.user
        # Retourne seulement les matchs non joués, non commencés, du club authentifié
        return RefMatch.objects.all().exclude(match_fini=True).filter(reprise=0).filter(lieu_organisation=utilisateur)
    
'''
def match_create(request):
    form = MatchCreateForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('list_match')
    return render(request, 'form_match.html', {"form": form})
'''


@login_required(login_url='../club/login/')
def match_update(request, pk):
    try:
        refmatch = RefMatch.objects.get(pk=pk)
    except refmatch.DoesNotExist:
        return redirect('list_match_updel')
    form = UpdateForm(request.POST or None, instance=refmatch)
    if form.is_valid():
        form.save()
        # Sauvegarde du club organisateur en récupérant le club authentifié
        refmatch.lieu_organisation = request.user
        refmatch.save()
        return redirect('list_match_updel')
    return render(request, 'form_match.html', {'form': form, 'refmatch': refmatch })
   
    def form_valid(self, form):
        form.instance.lieu_organisation = self.request.user
        return super().form_valid(form)


@login_required(login_url='../club/login/')
def match_delete(request, pk):
    try:
        refmatch = RefMatch.objects.get(pk=pk)
    except refmatch.DoesNotExist:
        return redirect('list_match_updel')
    form = MatchDeleteForm(request.POST or None, instance=refmatch)
    if form.is_valid():
        refmatch.delete()
        return redirect('list_match_updel')
    return render(request, 'match_delete.html', {'form': form, 'refmatch': refmatch})


"""
class MatchListPortable(ListView):
    template_name = 'listmatchportable.html'

    def get_queryset(self):
        return RefMatch.objects.all().exclude(match_fini=True)
"""


@login_required(login_url='../club/login/')
def match_detail(request, pk):
    refmatch = get_object_or_404(RefMatch, pk=pk)
    points = Points.objects.filter(match_id=refmatch)

    context = {"refmatch": refmatch, "point": points}
    return render(request, "match_view.html", context)


def quiCommence(request, pk):
    refmatch = get_object_or_404(RefMatch, pk=pk)
    form = ChoixJoueurForm(request.POST or None)

    if form.is_valid():
        form.save()
        return redirect('index')
#    else:
#        return redirect('index')

    return render(request, "qui_commence.html", {'form': form, 'refmatch': refmatch})


@login_required(login_url='../../club/login/')
def match_detail_portable(request, pk):
    refmatch = get_object_or_404(RefMatch, pk=pk)
    points = Points.objects.filter(match_id=refmatch)
    reprise = refmatch.reprise
    whiteball = refmatch.whiteball

    # l'incrémentation de la reprise se fait uniquement quand le joueur N°1 valide ces points
    if whiteball == True:
        refmatch.reprise = reprise + 1
    pointreprise = 0
    form = PointsForm()
    if request.method == 'POST':
        form = PointsForm(request.POST)
        if form.is_valid():
            points = Points(
                match=refmatch,
                reprise=refmatch.reprise,
                point=form.cleaned_data["point"],
                whiteball=whiteball,
            )
        pointreprise = points.point

        if whiteball == True:
            refmatch.whiteball = False
           # refmatch.reprise = reprise + 1
            refmatch.point_j1 = refmatch.point_j1 + pointreprise
            points.cumul_point = refmatch.point_j1
            # Test si la série est plus grande que celle présente dans la BDD
            # Si True enregistrement de la nouvelle série dans la BDD
            if pointreprise > refmatch.serie_j1:
                refmatch.serie_j1 = pointreprise
            # calcul de la moyenne
            refmatch.moyenne_j1 = refmatch.point_j1 / refmatch.reprise
        else:
            refmatch.whiteball = True
            refmatch.point_j2 = refmatch.point_j2 + pointreprise
            points.cumul_point = refmatch.point_j2
            # Test si la série est plus grande que celle présente dans la BDD
            # Si True enregistrement de la nouvelle série dans la BDD
            if pointreprise > refmatch.serie_j2:
                refmatch.serie_j2 = pointreprise
            # calcul de la moyenne
            refmatch.moyenne_j2 = refmatch.point_j2 / refmatch.reprise
        
        points.save()
        refmatch.save()
        pointj1 = refmatch.point_j1
        pointj2 = refmatch.point_j2
        distance = refmatch.distance.distance
        # Test 1 : Joueur 2 match fini ou Joueur 1 match fini + Joueur 2 a fait sa reprise ?
        if pointj2 == distance or (pointj1 == distance and pointj2 <= distance and refmatch.match_fini == True):
            refmatch.match_fini = True
            refmatch.save()
            return redirect('index')
        # Test 2 : Joueur 1 match fini ? (ce test est en N°2 pour que le Joueur 2 puisse faire sa reprise)
        if pointj1 == distance and refmatch.match_fini == False:
            refmatch.match_fini = True
            refmatch.save()
        
        form = PointsForm()

    context = {"refmatch": refmatch, "point": points, "form": form}
    return render(request, "match_view_portable.html", context)

