from django.shortcuts               import render
from django.urls                    import reverse_lazy
from django.views.generic           import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.utils.decorators        import method_decorator
from django.contrib.auth.decorators import login_required

from rest_framework             import viewsets, status, permissions
from rest_framework.views       import APIView
from rest_framework.response    import Response

from .models        import Equipment
from .serializers   import EquipmentSerializer
from .forms         import EquipmentForm
from .permissions   import IsOwner

@login_required
def list_active_equipments(request):
    equipments = Equipment.objects.filter(is_active=True)
    return render(request, "parc/list.html", {"equipments": equipments})

@method_decorator(login_required, name="dispatch")
class EquipmentListView(ListView):
    model = Equipment
    template_name = "parc/list.html"
    context_object_name = "equipments"

    def get_queryset(self):
        return Equipment.objects.filter(is_active=True)

@method_decorator(login_required, name="dispatch")
class EquipmentDetailView(DetailView):
    model = Equipment
    template_name = "parc/detail.html"
    context_object_name = "equipment"

@method_decorator(login_required, name="dispatch")
class EquipmentCreateView(CreateView):
    model = Equipment
    form_class = EquipmentForm
    template_name = "parc/form.html"
    success_url = reverse_lazy("equipment_list")

@method_decorator(login_required, name="dispatch")
class EquipmentUpdateView(UpdateView):
    model = Equipment
    form_class = EquipmentForm
    template_name = "parc/form.html"
    success_url = reverse_lazy("equipment_list")

@method_decorator(login_required, name="dispatch")
class EquipmentDeleteView(DeleteView):
    model = Equipment
    template_name = "parc/delete_confirm.html"
    success_url = reverse_lazy("equipment_list")

class EquipmentListAPIView(APIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get(self, request):
        equipments = Equipment.objects.all()
        serializer = EquipmentSerializer(equipments, many=True)

        return Response(serializer.data)

    def post(self, request):
        serializer = EquipmentSerializer(data=request.data)

        if serializer.is_valid():
            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class EquipmentViewSet(viewsets.ModelViewSet):
    """
    Ce ViewSet fournit automatiquement les actions :
    - 'list' (GET /equipments/)
    - 'retrieve' (GET /equipments/{id}/)
    - 'create' (POST /equipments/)
    - 'update' (PUT /equipments/{id}/)
    - 'destroy' (DELETE /equipments/{id}/)
    """
    permission_classes = [permissions.IsAuthenticated, IsOwner]

    def get_queryset(self):
        return Equipment.objects.filter(owner=self.request.user)
    
    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
    
    # queryset = Equipment.objects.all()
    serializer_class = EquipmentSerializer

import logging

logger = logging.getLogger("parc.auth")

class EquipmentViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, IsOwner]

    def get_queryset(self):
        return Equipment.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def handle_exception(self, exc):
        response = super().handle_exception(exc)
        if response.status_code in (401, 403):
            logger.warning(
                "Authentication failure: user=%s path=%s method=%s status=%s",
                getattr(self.request.user, "username", "anonymous"),
                self.request.path,
                self.request.method,
                response.status_code,
            )
        return response

    serializer_class = EquipmentSerializer
