from django.db.models import Q

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

from ichec_django_core.models import Member
from ichec_django_core.views import ObjectFileUploadView, SearchableModelViewSet

from ..models import (
    FacilityTestReport,
)

from ..serializers import (
    FacilityTestReportSerializer,
)


class FacilityTestReportViewSet(SearchableModelViewSet):
    model = FacilityTestReport
    queryset = FacilityTestReport.objects.all().order_by("id")
    serializer_class = FacilityTestReportSerializer
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
    ordering_fields = ("updated_at",)
    ordering: tuple[str, ...] = ("-updated_at",)
    search_fields = [
        "application__chosen_facility__name",
        "application__applicant__email",
        "creator__email",
    ]
    filterset_fields = ["application__call__id"]

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

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

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

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

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

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


class TestReportUploadView(ObjectFileUploadView):
    model = FacilityTestReport
    queryset = FacilityTestReport.objects.all()
    file_field = "report"
    extensions = (".odt", ".doc", ".docx", ".pdf", ".ods", ".xls", ".xlsx")
    permission_classes = [
        permissions.IsAuthenticated,
        permissions.DjangoModelPermissions,
    ]
