from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from notifications.models import Notification
from notifications.serializers import NotificationSerializer


class NotificationViewSet(ReadOnlyModelViewSet):
    serializer_class = NotificationSerializer

    def get_queryset(self):
        return Notification.objects.filter(Q(recipient=self.request.user) | Q(recipient__isnull=True))

    @action(methods=['POST'], detail=True)
    def read(self, request, *args, **kwargs):
        """Make notification is read"""

        notification = self.get_object()
        notification.is_read = True
        notification.save()
        data = NotificationSerializer(instance=notification).data
        return Response(data)
