from rest_framework import permissions

from ichec_django_core.models import Feedback, Member

from ichec_django_core.serializers import FeedbackSerializer

from .permissions import OwnerFullOrDjangoModelPermissions
from .core import BaseModelViewSet


class CreatorFullOrDjangoModelPermissions(OwnerFullOrDjangoModelPermissions):
    owner_field = "creator"


class FeedbackViewSet(BaseModelViewSet):

    model = Feedback
    queryset = Feedback.objects.all().order_by("id")
    serializer_class = FeedbackSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        CreatorFullOrDjangoModelPermissions,
    ]
    filterset_fields = ("creator__id",)

    def filter_self(self, queryset):
        return queryset.filter(creator__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.
        """
        return self.filter_self_or_permission(super().get_queryset())

    def perform_create(self, serializer):
        serializer.save(creator=Member.objects.get(id=self.request.user.id))
