from rest_framework import permissions

from ichec_django_core.models import Notification
from ichec_django_core.serializers import NotificationSerializer

from .core import BaseModelViewSet
from .permissions import SelfEditOrDjangoModelPermissions


class NotificationViewSet(BaseModelViewSet):

    queryset = Notification.objects.all()
    serializer_class = NotificationSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        SelfEditOrDjangoModelPermissions,
    ]

    def filter_self(self, queryset):
        return queryset.filter(user__id=self.request.user.id)

    def get_queryset(self):
        """
        If the user has view permissions for this model then return all objects,
        otherwise filter by their own objects only.
        """

        queryset = Notification.objects.all().order_by("id")

        unread = self.request.query_params.get("unread")
        if unread is not None:
            queryset = queryset.filter(read_time=None)

        return self.filter_self_or_permission(queryset, Notification)
