from django.db import IntegrityError
from rest_framework.views import APIView
from rest_framework.response import Response
from playlist.models import Vote, Profile
from playlist.serializers import VoteSerializer, VoteSaveSerializer

class VoteListView(APIView):
    def get(self, request, user_id = None):
        if user_id:
            votes = Vote.objects.filter(user_id=user_id)
        else:
            votes = Vote.objects.all()
        serializer = VoteSerializer(votes, many=True, context={'request': request})
        return Response(serializer.data)

    def post(self, request):
        (profile,_) = Profile.objects.get_or_create(user=request.user)
        if not profile.can_vote:
            return Response({'error': 'User cannot vote'}, status=403)
        serializer = VoteSaveSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            try:
                serializer.save(user=request.user)
                return Response(serializer.data, status=201)
            except IntegrityError:
                return Response({'error': 'Duplicate vote'}, status=400)
        return Response(serializer.errors, status=400)

    def delete(self, request):
        if request.user.is_superuser:
            Vote.objects.all().delete()
            return Response(status=204)
        else:
            return Response(status=403)

class VoteDetailView(APIView):
    def get(self, request, id):
        vote = Vote.objects.get(pk=id)
        serializer = VoteSerializer(vote, context={'request': request})
        return Response(serializer.data)
