from django.db import IntegrityError
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import DetailView, FormView, ListView, TemplateView

from .forms import JobApplicationForm
from .models import JobApplication, JobOffer


class JobListView(ListView):
    template_name = 'careers/job_list.html'
    context_object_name = 'jobs'

    def get_queryset(self):
        qs = JobOffer.objects.filter(status=JobOffer.Status.PUBLISHED)
        dept = self.request.GET.get('dept')
        if dept:
            qs = qs.filter(department=dept)
        return qs

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['departments'] = JobOffer.Department.choices
        ctx['active_dept'] = self.request.GET.get('dept', '')
        return ctx


class JobDetailView(DetailView):
    template_name = 'careers/job_detail.html'
    context_object_name = 'job'

    def get_object(self):
        return get_object_or_404(JobOffer, slug=self.kwargs['slug'], status=JobOffer.Status.PUBLISHED)


class ApplyView(FormView):
    template_name = 'careers/apply.html'
    form_class = JobApplicationForm

    def dispatch(self, request, *args, **kwargs):
        self.job = get_object_or_404(JobOffer, slug=kwargs['slug'], status=JobOffer.Status.PUBLISHED)
        if not self.job.is_open:
            return redirect('careers:job_detail', slug=self.job.slug)
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['job'] = self.job
        return ctx

    def form_valid(self, form):
        application = form.save(commit=False)
        application.job = self.job
        try:
            application.save()
        except IntegrityError:
            form.add_error('email', 'Vous avez déjà postulé à cette offre avec cet email.')
            return self.form_invalid(form)
        return redirect('careers:apply_success', slug=self.job.slug)


class ApplySuccessView(TemplateView):
    template_name = 'careers/apply_success.html'

    def get_context_data(self, **kwargs):
        ctx = super().get_context_data(**kwargs)
        ctx['job'] = get_object_or_404(JobOffer, slug=self.kwargs['slug'])
        return ctx
