from rest_framework.views import APIView
from rest_framework.response import Response
from playlist.models import Track, Profile
from playlist.serializers import TrackSerializer
from playlist.spotify import spt
from playlist.tasks import get_banter, get_and_dither_image

class TrackListView(APIView):
    def get(self, request):
        tracks = Track.objects.all()
        serializer = TrackSerializer(tracks, many=True, context={'request': request})
        return Response(serializer.data)

    def post(self, request):
        (profile, _) = Profile.objects.get_or_create(user=request.user)
        (can_nom, reason) = profile.can_nominate
        if not can_nom:
            return Response({'error': reason}, status=403)
        (track, message) = Track.objects.create_from_spotify(request.data['spotify_link'], profile)
        serializer = TrackSerializer(track, context={'request': request})
        return Response(serializer.data)

    def delete(self, request):
        if request.user.is_superuser:
            Track.objects.all().delete()
            return Response(status=204)
        else:
            return Response({'error': 'Only superusers can delete all tracks'}, status=403)

class TrackDetailView(APIView):
    def get(self, request, id):
        track = Track.objects.get(pk=id)
        serializer = TrackSerializer(track, context={'request': request})
        return Response(serializer.data)
