import os
from django.urls import reverse_lazy
from django.views import View
from enquetes.models import Enquete
from .models import Reunion, Participant
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import CreateView, ListView, DetailView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from REUNION import settings
from .forms import *


@csrf_exempt
def upload_image(request):
    if request.method != 'POST':
        return JsonResponse({'Error Message':'Mauvaise requete'})

    file_obj = request.FILES['file']
    extension = file_obj.name.split('.')[-1]
    if extension not in ['jpg', 'png', 'gif', 'jpeg']:
        return JsonResponse({'Error Message':'Merci de prendre un fichier jpeg, png gif ou jpeg'})
    chemin = os.path.join(settings.MEDIA_ROOT, 'imagereunion', file_obj.name)

    with open(chemin, 'wb+') as f:
        for chunk in file_obj.chunks():
            f.write(chunk)
        return JsonResponse({
            'Message':'Image importée',
            'location': os.path.join(settings.MEDIA_URL, 'imagereunion', file_obj.name)
        })


class CreateReunionCecleView(LoginRequiredMixin, CreateView):
    model = Reunion
    template_name = 'ajoutreunioncercle.html'
    form_class = CreateReunionForm

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.type_reunion = 'ReunionCercle'
        return super().form_valid(form)


class CreateReunionCoordView(LoginRequiredMixin, CreateView):
    model = Reunion
    template_name = 'ajoutreunioncoord.html'
    form_class = CreateReunionForm

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.type_reunion = 'ReunionCoordination'
        return super().form_valid(form)


class CreateDialoguedView(LoginRequiredMixin, CreateView):
    model = Reunion
    template_name = 'ajoutdialogue.html'
    form_class = CreateReunionForm

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.instance.type_reunion = 'DialogueCommunautaire'
        return super().form_valid(form)


class ListeReunionCercle(ListView, LoginRequiredMixin):
    model = Reunion
    template_name = 'listereunioncercle.html'
    context_object_name = 'reunions'
    paginate_by = 20

    def get_queryset(self):
        return Reunion.objects.filter(type_reunion='ReunionCercle')


class ListeReunionCoordination(LoginRequiredMixin, ListView):
    model = Reunion
    template_name = 'listereunioncoordination.html'
    context_object_name = 'reunions'
    paginate_by = 20

    def get_queryset(self):
        return Reunion.objects.filter(type_reunion='ReunionCoordination')


class ListeDialogueCommunautaire(LoginRequiredMixin,ListView):
    model = Reunion
    template_name = 'listdialoguecommunautaire.html'
    context_object_name = 'reunions'
    paginate_by = 20

    def get_queryset(self):
        return Reunion.objects.filter(type_reunion='ReunionCoordination')


class ReunionDetailView(LoginRequiredMixin, DetailView):
    model = Reunion
    template_name = 'datailreunion.html'
    context_object_name = 'reunion'

    def get_object(self, queryset=None):
        return get_object_or_404(Reunion, id=self.kwargs['id'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        reunion = self.get_object()

        # Comptage des participants par sexe
        participants_h = Participant.objects.filter(reunion=reunion, sexe='H').count()
        participants_f = Participant.objects.filter(reunion=reunion, sexe='F').count()
        total_participants = participants_h + participants_f

        # Calcul des pourcentages
        if total_participants > 0:
            percent_h = round((participants_h / total_participants) * 100, 2)
            percent_f = round((participants_f / total_participants) * 100, 2)
        else:
            percent_h = percent_f = 0  # Éviter une division par zéro

        # Ajout des données au contexte
        context.update({
            'participants': Participant.objects.filter(reunion=reunion),
            'participantsh': participants_h,
            'participantsf': participants_f,
            'participantsc': total_participants,
            'percent_h': percent_h,
            'percent_f': percent_f,
        })

        # Gestion de l'enquête associée
        try:
            context['enquete'] = Enquete.objects.get(reunion=reunion)
        except Enquete.DoesNotExist:
            context['enquete'] = None

        return context


class AjouParticipant(LoginRequiredMixin, CreateView):
    model = Participant
    template_name = 'ajoutparticipant.html'
    form_class = AjoutParticipanForm

    def get_success_url(self):
        # Utiliser l'ID de la réunion pour construire l'URL
        return reverse_lazy('reunion:detail_reunion', kwargs={'id': self.kwargs['id']})

    def get_object(self, queryset=None):
        # Charger la réunion associée à l'ID passé en paramètre
        return get_object_or_404(Reunion, id=self.kwargs['id'])

    def form_valid(self, form):
        # Associer le participant à la réunion avant de l'enregistrer
        form.instance.reunion = self.get_object()
        return super().form_valid(form)


class AjoutCompteRendu(LoginRequiredMixin, UpdateView):
    model = Reunion
    template_name = 'compte_rendu.html'  # Remplace par le chemin de ton template
    form_class = Ajout_resume

    def get_object(self, queryset=None):
        return get_object_or_404(Reunion, id=self.kwargs['id'])

    def get_success_url(self):
        return reverse_lazy('reunion:detail_reunion', kwargs={'id': self.object.id})  # Redirige vers la page des détails


# Vue pour terminer une réunion
class TerminerReunion(LoginRequiredMixin, View):
    def post(self, request, *args, **kwargs):
        reunion = get_object_or_404(Reunion, id=self.kwargs['id'])
        reunion.statut = Reunion.STATUT_CHOICES.TERMINE
        reunion.save()
        return HttpResponseRedirect(reverse_lazy('reunion:detail_reunion', kwargs={'id': reunion.id}))


class ResumeReunion(LoginRequiredMixin,DetailView):
    model = Reunion
    template_name = 'resumereunion.html'

    def get_object(self, queryset=None):
        return get_object_or_404(Reunion, id=self.kwargs['id'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        reunion =self.get_object()
        context['reunion'] = reunion
        try:
            context['enquete'] = Enquete.objects.get(reunion=reunion)
        except Enquete.DoesNotExist:
            context[
                'enquete'] = None  # Ou omettez complètement cette ligne si vous n'avez pas besoin de définir une valeur par défaut
        return context


class PlanificationCreateView(LoginRequiredMixin, CreateView):
    model = PlanificationMensuel
    form_class = PlanificationMensuelForm
    template_name = "planification_form.html"  # Un template pour le formulaire
    success_url = reverse_lazy("reunion:list_planification")  # Redirection après soumission

    def form_valid(self, form):
        """ Vérifie si une planification existe déjà pour ce mois et cette zone """
        mois = form.cleaned_data["mois"]
        zone = form.cleaned_data["zone"]

        if PlanificationMensuel.objects.filter(mois=mois, zone=zone).exists():
            form.add_error(None, "Une planification existe déjà pour cette zone et ce mois.")
            return self.form_invalid(form)

        return super().form_valid(form)


class ListPlanification(LoginRequiredMixin, ListView):
    model = PlanificationMensuel
    template_name = 'listplanification.html'
    context_object_name = 'planifications'
    paginate_by = 50

    def get_queryset(self):
        return PlanificationMensuel.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['zones'] = ZoneReunion.objects.all()
        return context
