from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.urls import reverse_lazy
from django.views import generic

from .models import Department
from .management_forms import DepartmentForm

class DepartmentListView(LoginRequiredMixin, UserPassesTestMixin, generic.ListView):
    model = Department
    template_name = 'users/department_list.html'
    context_object_name = 'departments'
    
    def test_func(self):
        return self.request.user.is_staff

class DepartmentDetailView(LoginRequiredMixin, UserPassesTestMixin, generic.DetailView):
    model = Department
    template_name = 'users/department_detail.html'
    context_object_name = 'department'
    
    def test_func(self):
        return self.request.user.is_staff

class DepartmentCreateView(LoginRequiredMixin, UserPassesTestMixin, generic.CreateView):
    model = Department
    form_class = DepartmentForm
    template_name = 'users/department_form.html'
    success_url = reverse_lazy('users:department_list')
    
    def test_func(self):
        return self.request.user.is_staff
    
    def form_valid(self, form):
        messages.success(self.request, 'Department created successfully.')
        return super().form_valid(form)

class DepartmentUpdateView(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView):
    model = Department
    form_class = DepartmentForm
    template_name = 'users/department_form.html'
    
    def test_func(self):
        return self.request.user.is_staff
    
    def get_success_url(self):
        return reverse_lazy('users:department_detail', kwargs={'pk': self.object.pk})
    
    def form_valid(self, form):
        messages.success(self.request, 'Department updated successfully.')
        return super().form_valid(form)

class DepartmentDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):
    model = Department
    template_name = 'users/department_confirm_delete.html'
    success_url = reverse_lazy('users:department_list')
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def delete(self, request, *args, **kwargs):
        messages.success(request, 'Department deleted successfully.')
        return super().delete(request, *args, **kwargs)
