from rest_framework import serializers
from playlist.models import Vote, Track

class VoteSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Vote
        fields = '__all__'
        extra_kwargs = {
            'url': {'view_name': 'api-vote', 'lookup_field': 'id'},
            'track': {'view_name': 'api-track', 'lookup_field': 'id'},
            'user': {'view_name': 'api-user', 'lookup_field': 'id'}
        }

class VoteSaveSerializer(serializers.ModelSerializer):
    class Meta:
        model = Vote
        fields = ['track', 'points', 'skipped']

    def create(self, validated_data):
        """
        Create a new vote. Deletes a previous skipped vote if it exists.
        """
        user = self.context['request'].user
        track = validated_data['track']
        previous_vote = Vote.objects.filter(user=user, track=track).first()
        if previous_vote and previous_vote.skipped:
            previous_vote.delete()
        return Vote.objects.create(**validated_data)
