from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.parsers import MultiPartParser, FormParser
from .models import Photo, Category, Album
from .serializers import PhotoSerializer, CategorySerializer, AlbumSerializer

class CategoryViewSet(viewsets.ModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class AlbumViewSet(viewsets.ModelViewSet):
    queryset = Album.objects.all().order_by('-created_at')
    serializer_class = AlbumSerializer
    
    @action(detail=True, methods=['post'])
    def add_photos(self, request, pk=None):
        """Add photos to an album"""
        album = self.get_object()
        photo_ids = request.data.get('photo_ids', [])
        
        photos = Photo.objects.filter(id__in=photo_ids)
        album.photos.add(*photos)
        
        return Response({
            'status': 'photos added',
            'photo_count': album.photo_count
        })
    
    @action(detail=True, methods=['post'])
    def remove_photos(self, request, pk=None):
        """Remove photos from an album"""
        album = self.get_object()
        photo_ids = request.data.get('photo_ids', [])
        
        photos = Photo.objects.filter(id__in=photo_ids)
        album.photos.remove(*photos)
        
        return Response({
            'status': 'photos removed',
            'photo_count': album.photo_count
        })
    
    @action(detail=True, methods=['get'])
    def photos(self, request, pk=None):
        """Get all photos in an album"""
        album = self.get_object()
        photos = album.photos.all()
        serializer = PhotoSerializer(photos, many=True)
        return Response(serializer.data)

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all().order_by('-uploaded_at')
    serializer_class = PhotoSerializer
    parser_classes = (MultiPartParser, FormParser)

    def create(self, request, *args, **kwargs):
        # Handle multiple file uploads
        if 'photos' in request.FILES:
            photos_data = []
            category_id = request.data.get('category')
            album_ids = request.data.getlist('albums', [])
            
            category = None
            if category_id:
                try:
                    category = Category.objects.get(id=category_id)
                except Category.DoesNotExist:
                    pass

            for file in request.FILES.getlist('photos'):
                photo = Photo.objects.create(
                    title=file.name,
                    image=file,
                    category=category
                )
                
                # Add to albums if specified
                if album_ids:
                    albums = Album.objects.filter(id__in=album_ids)
                    photo.albums.add(*albums)
                
                photos_data.append(PhotoSerializer(photo).data)
            
            return Response(photos_data, status=status.HTTP_201_CREATED)
            
        return super().create(request, *args, **kwargs)

    @action(detail=True, methods=['post'])
    def favorite(self, request, pk=None):
        photo = self.get_object()
        photo.is_favorite = not photo.is_favorite
        photo.save()
        return Response({'status': 'favorite toggled', 'is_favorite': photo.is_favorite})