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 UserRole
from .management_forms import UserRoleForm

class RoleListView(LoginRequiredMixin, UserPassesTestMixin, generic.ListView):
    model = UserRole
    template_name = 'users/role_list.html'
    context_object_name = 'roles'
    
    def test_func(self):
        return self.request.user.is_superuser

class RoleDetailView(LoginRequiredMixin, UserPassesTestMixin, generic.DetailView):
    model = UserRole
    template_name = 'users/role_detail.html'
    context_object_name = 'role'
    
    def test_func(self):
        return self.request.user.is_superuser

class RoleCreateView(LoginRequiredMixin, UserPassesTestMixin, generic.CreateView):
    model = UserRole
    form_class = UserRoleForm
    template_name = 'users/role_form.html'
    success_url = reverse_lazy('users:role_list')
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def form_valid(self, form):
        messages.success(self.request, 'Role created successfully.')
        return super().form_valid(form)

class RoleUpdateView(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView):
    model = UserRole
    form_class = UserRoleForm
    template_name = 'users/role_form.html'
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def get_success_url(self):
        return reverse_lazy('users:role_detail', kwargs={'pk': self.object.pk})
    
    def form_valid(self, form):
        messages.success(self.request, 'Role updated successfully.')
        return super().form_valid(form)

class RoleDeleteView(LoginRequiredMixin, UserPassesTestMixin, generic.DeleteView):
    model = UserRole
    template_name = 'users/role_confirm_delete.html'
    success_url = reverse_lazy('users:role_list')
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def delete(self, request, *args, **kwargs):
        messages.success(request, 'Role deleted successfully.')
        return super().delete(request, *args, **kwargs)
