from django.shortcuts import render

from django.shortcuts import render
from django.views.generic.list import ListView
from rest_framework import generics, status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .models import Vehicle
from .serializers import VehicleSerializer
from scalesapp.sse import broadcast_update

# Create your views here.
class CountriesView(ListView):
    pass

# API Views
class VehicleListCreateAPIView(generics.ListCreateAPIView):
    queryset =Vehicle.objects.all()
    serializer_class = VehicleSerializer
    permission_classes = [IsAuthenticated]
    
    def create(self, request, *args, **kwargs):
        """Override create to broadcast SSE message"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        # Broadcast SSE update
        broadcast_update('vehicle', 'created', serializer.data)
        
        return Response(serializer.data, status=status.HTTP_201_CREATED)

class VehicleRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Vehicle.objects.all()
    serializer_class = VehicleSerializer
    permission_classes = [IsAuthenticated]
    
    def update(self, request, *args, **kwargs):
        """Override update to broadcast SSE message"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        # Broadcast SSE update
        broadcast_update('vehicle', 'updated', serializer.data)
        
        return Response(serializer.data)
    
    def destroy(self, request, *args, **kwargs):
        """Override destroy to broadcast SSE message"""
        instance = self.get_object()
        country_data = CountrySerializer(instance).data
        self.perform_destroy(instance)
        
        # Broadcast SSE update
        broadcast_update('vehicle', 'deleted', country_data)
        
        return Response(status=status.HTTP_204_NO_CONTENT)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def get_vehicles(request):
    """API endpoint for getting countries list"""
    vehicles = Vehicle.objects.all().order_by('id')
    serializer = VehicleSerializer(vehicles, many=True)
    return Response(serializer.data)