from django.db.models import Q

from rest_framework import permissions, viewsets
from rest_framework.decorators import action

from ichec_django_core.views import (
    ObjectFileUploadView,
    BaseModelViewSet,
)

from ..models import (
    AccessApplicationFacilityReview,
)

from ..serializers import (
    AccessApplicationFacilityReviewSerializer,
)


class AccessApplicationFacilityReviewViewSet(BaseModelViewSet):
    queryset = AccessApplicationFacilityReview.objects.all().order_by("id")
    serializer_class = AccessApplicationFacilityReviewSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]

    @action(detail=True, url_path="supporting_document", url_name="supporting_document")
    def supporting_document(self, request, pk=None):
        return self.download(request, "supporting_documents")

    def get_queryset(self):
        """
        If user has explicit Django view permissions return
        all reviews.

        Otherwise return reviews where the user is the coordinator,
        chair or member of the facility
        """

        if self.has_model_view_permission():
            return viewsets.ModelViewSet.get_queryset(self)

        queryset = viewsets.ModelViewSet.get_queryset(self)
        queryset = queryset.filter(
            Q(application__call__board_chair__id=self.request.user.id)
            | Q(facility__members__id=self.request.user.id)
            | Q(application__call__coordinator__id=self.request.user.id)
        ).distinct()
        return queryset


class AccessApplicationFacilityReviewSupportingDocumentUploadView(ObjectFileUploadView):
    model = AccessApplicationFacilityReview
    queryset = AccessApplicationFacilityReview.objects.all()
    file_field = "supporting_documents"
    extensions = (".odt", ".doc", ".docx", ".pdf")
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
