from rest_framework import serializers

from ichec_django_core.serializers.core import SERIALIZER_BASE_FIELDS

from marinerg_test_access.models import (
    FacilityTestReport,
)


class FacilityTestReportSerializer(serializers.HyperlinkedModelSerializer):

    report = serializers.HyperlinkedIdentityField(
        read_only=True, view_name="facilitytestreport-report"
    )

    class Meta:
        model = FacilityTestReport
        fields = SERIALIZER_BASE_FIELDS + (
            "creator",
            "report",
            "datasets",
            "confirmed_complies_data_mgmt",
            "application",
            "facility",
            "facility_name",
            "facility_acronym",
            "call_title",
            "applicant_contact",
            "creator_contact",
        )
        read_only_fields = SERIALIZER_BASE_FIELDS + (
            "creator",
            "report",
            "facility_name",
            "facility_acronym",
            "facility_contact",
            "call_title",
            "creator_contact",
        )

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if not instance.report:
            rep["report"] = None
        return rep

    def _is_facility_member(self, application) -> bool:
        request = self.context.get("request", None)

        if not application.chosen_facility:
            return False
        for member in application.chosen_facility.members.all():
            if member.id == request.user.id:
                return True
        return False

    def _already_submitted(self, application) -> bool:
        return (
            FacilityTestReport.objects.filter(application__id=application.id).count()
            > 0
        )

    def create(self, validated_data):

        if not self._is_facility_member(validated_data["application"]):
            raise serializers.ValidationError(
                {"facility": "Only facility members can create reports"}
            )

        if self._already_submitted(validated_data["application"]):
            raise serializers.ValidationError(
                {"creator": "This application already has a report"}
            )

        return super().create(validated_data)
