from django.contrib.auth.models import Group

from rest_framework import viewsets

from ichec_django_core.serializers import GroupDetailSerializer, GroupListSerializer

from .core import SearchableModelViewSet
from .permissions import CustomDjangoModelPermissions, get_permission


class GroupPermissions(CustomDjangoModelPermissions):

    intercept_methods = ["GET"]
    allow_django_fallback = False

    def object_perm_check(self, obj, request) -> bool:
        return request.user.has_perm(get_permission(Group, "view"))


class GroupViewSet(SearchableModelViewSet):
    model = Group
    queryset = Group.objects.all()
    serializer_class = GroupListSerializer
    permission_classes = [GroupPermissions]

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

    serializers = {
        "retrieve": GroupDetailSerializer,
        "list": GroupListSerializer,
        "create": GroupDetailSerializer,
        "update": GroupDetailSerializer,
        "partial_update": GroupDetailSerializer,
    }

    def get_queryset(self):
        """
        Public users can only see public Orgs
        Registered users can see pubic Orgs or orgs they are members of
        Users with view permission can see all Orgs
        """

        queryset = viewsets.ModelViewSet.get_queryset(self)

        if not self.has_model_view_permission():
            queryset = queryset.filter(user__id=self.request.user.id)

        user_id = self.request.query_params.get("user")
        if user_id is not None:
            queryset = queryset.filter(user__id=user_id)
        return queryset
