"""API views for social_network."""

from rest_framework import viewsets
from rest_framework.decorators import api_view, detail_route
from rest_framework.response import Response
from rest_framework.reverse import reverse

from .models import Profile, Post, Vote
from .serializers import ProfileSerializer, PostSerializer


@api_view(['GET'])
def api_root(request, format=None):
    """Root of API, this is useful for documentation generated by DRF."""
    return Response({
        'profiles': reverse('profile-list', request=request, format=format),
        'posts': reverse('post-list', request=request, format=format)
    })


class ProfileViewSet(viewsets.ReadOnlyModelViewSet):
    """This provides get and list functionality for Profiles."""

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class PostViewSet(viewsets.ModelViewSet):
    """This provides r/w access to Posts."""

    queryset = Post.objects.all().order_by('-created')
    serializer_class = PostSerializer

    def perform_create(self, serializer):
        """Create a Post associated with the logged-in user."""
        serializer.save(owner=self.request.user.profile)

    @detail_route(methods=['POST'], url_path='vote')
    def vote(self, request, pk=None):
        """Vote on a post."""
        post = self.get_object()
        # check if the vote already exists, if so don't allow the user to vote again
        if Vote.objects.filter(profile=self.request.user.profile, post=post).exists():
            # the user already voted, just return the post directly
            data = PostSerializer(post, context={'request': self.request}).data
            return Response(data)

        new_vote = Vote(profile=self.request.user.profile, post=post)
        new_vote.save()
        data = PostSerializer(post, context={'request': self.request}).data
        return Response(data)

    @detail_route(methods=['DELETE'], url_path='vote')
    def unvote(self, request, pk=None):
        """Remove a Vote on a post."""
        post = self.get_object()
        Vote.objects.filter(profile=self.request.user.profile, post=post).delete()
        data = PostSerializer(post, context={'request': self.request}).data
        return Response(data)

"""API views for social_network."""

from rest_framework import viewsets
from rest_framework.decorators import api_view, detail_route
from rest_framework.response import Response
from rest_framework.reverse import reverse

from .models import Profile, Post, Vote
from .serializers import ProfileSerializer, PostSerializer


@api_view(['GET'])
def api_root(request, format=None):
    """Root of API, this is useful for documentation generated by DRF."""
    return Response({
        'profiles': reverse('profile-list', request=request, format=format),
        'posts': reverse('post-list', request=request, format=format)
    })


class ProfileViewSet(viewsets.ReadOnlyModelViewSet):
    """This provides get and list functionality for Profiles."""

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer


class PostViewSet(viewsets.ModelViewSet):
    """This provides r/w access to Posts."""

    queryset = Post.objects.all().order_by('-created')
    serializer_class = PostSerializer

    def perform_create(self, serializer):
        """Create a Post associated with the logged-in user."""
        serializer.save(owner=self.request.user.profile)

    @detail_route(methods=['POST', 'DELETE'], url_path='vote')
    def vote(self, request, pk=None):
        """Vote or unvote on a post."""
        post = self.get_object()
        if request.method == 'POST':
            # check if the vote already exists, if so don't allow the user to vote again
            if Vote.objects.filter(profile=self.request.user.profile, post=post).exists():
                # the user already voted, just return the post directly
                data = PostSerializer(post, context={'request': self.request}).data
                return Response(data)
            new_vote = Vote(profile=self.request.user.profile, post=post)
            new_vote.save()

        elif request.method == 'DELETE':
            Vote.objects.filter(profile=self.request.user.profile, post=post).delete()

        data = PostSerializer(post, context={'request': self.request}).data
        return Response(data)

Fix vote route when DELETE was overriding the POST