from rest_framework import permissions, viewsets
from rest_framework import filters

from ichec_django_core.models import Organization, Address

from ichec_django_core.serializers import (
    OrganizationDetailSerializer,
    OrganizationListSerializer,
    AddressSerializer,
)


class MemberEditOrDjangoModelPermissions(permissions.DjangoModelPermissions):

    def has_permission(self, request, view):

        if not request.user or not request.user.is_authenticated:
            return False

        # Fall through to allow edit permission checks to happen at object level
        if request.method in ["PUT", "PATCH"]:
            return True

        return super().has_permission(request, view)

    def has_object_permission(self, request, view, obj):

        # Allow metadata checks on endpoint
        if request.method in ["HEAD", "OPTIONS"]:
            return True

        if not request.user or not request.user.is_authenticated:
            return False

        # Edit permissions are only given to org members.
        if request.method in ["PUT", "PATCH"] and request.user.id in [
            m.id for m in obj.members
        ]:
            return True

        # Fall back to Django model permissions for everyone else
        return super().has_permission(request, view)


class OrganizationViewSet(viewsets.ModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrganizationListSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
    filter_backends = [filters.OrderingFilter, filters.SearchFilter]
    ordering_fields = ["name"]
    ordering = ["name"]
    search_fields = ["name", "address__line1", "address__country", "address__region"]

    serializers = {
        "retrieve": OrganizationDetailSerializer,
        "list": OrganizationListSerializer,
        "create": OrganizationDetailSerializer,
        "update": OrganizationDetailSerializer,
        "partial_update": OrganizationDetailSerializer,
    }

    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]

    def get_serializer_class(self):
        if hasattr(self, "serializers"):
            return self.serializers.get(self.action, self.serializer_class)
        return super().get_serializer_class()


class AddressViewSet(viewsets.ModelViewSet):
    queryset = Address.objects.all().order_by("id")
    serializer_class = AddressSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
