from django.db.models import Q

from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions

from ichec_django_core.models import Member
from ichec_django_core.views import (
    SearchableModelViewSet,
    PublicViewOwnerFullOrDjangoModelPermissions,
)

from marinerg_data_access.models import Dataset, DatasetTag, DatasetIdAuthority
from marinerg_data_access.serializers import (
    DatasetSerializer,
    DatasetTagSerializer,
    DatasetIdAuthoritySerializer,
)


class DatasetPermissions(PublicViewOwnerFullOrDjangoModelPermissions):
    owner_field = "creator"


class DatasetIdAuthorityViewSet(SearchableModelViewSet):
    queryset = DatasetIdAuthority.objects.all()
    serializer_class = DatasetIdAuthoritySerializer
    permission_classes = [permissions.DjangoModelPermissions]

    ordering_fields = SearchableModelViewSet.ordering_fields
    ordering: tuple[str, ...] = ("name",)
    search_fields = ["name"]


class DatasetViewSet(SearchableModelViewSet):
    model = Dataset
    queryset = Dataset.objects.all()
    serializer_class = DatasetSerializer
    permission_classes = [
        DatasetPermissions,
    ]

    ordering_fields = SearchableModelViewSet.ordering_fields
    ordering: tuple[str, ...] = ("created_at",)
    search_fields = ["title", "facility__name", "equipment__name"]

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

    def get_queryset(self):
        """
        Public users can only see public Datasets
        Registered users can see pubic dataset or orgs they created
        Users with view permission can see all Datasets
        """

        queryset = ModelViewSet.get_queryset(self)

        if not self.request.user.is_authenticated:
            return queryset.filter(public=True)

        if self.has_model_view_permission():
            return queryset

        return queryset.filter(
            Q(public=True) | Q(creator__id=self.request.user.id)
        ).distinct()


class DatasetTagViewSet(SearchableModelViewSet):
    queryset = DatasetTag.objects.all()
    serializer_class = DatasetTagSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
    ordering_fields = ("value",)
    ordering: tuple[str, ...] = ("value",)
    search_fields = ["value"]
    filterset_fields = ("dataset__id",)
