from django.shortcuts import render, get_object_or_404, redirect
from .models import Formulaire
from django.views.generic import ListView, DetailView
from django.db.models import Q
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
# Create your views here.
# def home(request):
#     etat = {
#         'status' : 'En cours de développement',
#     }
#     data = {
#         'formulaires' : Formulaire.objects.all()
#     }
#     return render(request,'index.html',data,etat)

def detail(request,id):
    data = {
        'form' : get_object_or_404(Formulaire,pk=id)
    }
    return render(request,'detail.html',data)

class Acceuil(LoginRequiredMixin,ListView):
    template_name = 'index.html'
    model = Formulaire
    context_object_name = 'formulaires'

    def get_queryset(self):
        contacts = super().get_queryset()
        return contacts.filter(manager = self.request.user)

# class FormDetailView(DetailView):
#     template_name = 'detail.html'
#     model = Formulaire
#     context_object_name = 'form'
@login_required
def search(request):
    if request.GET:
        search_term = request.GET['search_term']
        search_result = Formulaire.objects.filter(
            Q(name__icontains=search_term) |
            Q(info__icontains=search_term) |
            Q(email__icontains=search_term) |
            Q(phone__iexact=search_term)
            )

        recherche = {
            'search_term' : search_term,
            'formulaires' : search_result.filter(manager = request.user)
        }
        return render(request,'search.html',recherche)
    else:
        return render('acceuil')

class FormCreateView(LoginRequiredMixin,CreateView):
    model = Formulaire
    template_name = 'create.html'
    fields = ['name','email','phone','info','gender','image']
    # sucess_url = '/'
    def form_valid(self,form):
        instance = form.save(commit=False)
        instance.manager = self.request.user
        instance.save()
        return redirect('detail',instance.pk)

class FormUpdateView(LoginRequiredMixin,UpdateView):
    model = Formulaire
    template_name = 'update.html'
    fields = ['name','email','phone','info','gender','image']

    def form_valid(self,form):
        instance = form.save()
        return redirect('detail',instance.pk)

    def form_valid(self,form):
        instance = form.save()
        return redirect('detail',instance.pk)

class FormDeleteView(LoginRequiredMixin,DeleteView):
    model = Formulaire
    template_name = 'delete.html'
    success_url = '/'

class SignUpView(CreateView):
    form_class = UserCreationForm
    template_name = 'registration/signup.html'
    success_url = reverse_lazy('acceuil')
