"""This module holds api viewsets for ``likes`` app."""

from rest_framework import status, viewsets
from rest_framework.decorators import detail_route
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from .serializers import LikeSerializer

from ..constants import LIKE_DEFAULT_WEIGHT


class LikeableViewSet(viewsets.ModelViewSet):
    """ViewSet for ``Likeable`` model. To use like a mixin.

    Apply on a likeable model viewset to allow the record of likes with `.../likes` end point.

    """

    @detail_route(methods=['post', 'delete'], permission_classes=[IsAuthenticated])
    def likes(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """Create/Delete a like on current object from the authenticated user.

        For the parameters, see ``rest_framework.viewsets.ModelViewSet``.

        """

        if self.request.method == 'POST':
            like = self.request.user.like(
                self.get_object(),
                request.POST.get('weight', LIKE_DEFAULT_WEIGHT),
            )

            return Response(LikeSerializer(like).data)
        else:
            self.request.user.unlike(self.get_object())
            return Response(status=status.HTTP_204_NO_CONTENT)
