from rest_framework.response import Response
from rest_framework.generics import GenericAPIView

from huscy.xml.serializers import ParticipationsSerializer, ParticipationStatusSerializer
from huscy.xml.services import get_participation_status_xml, get_participations_xml
from mpi_cbs.huscy.subjects_wrapper.models import WrappedSubject


class ParticipationsXMLView(GenericAPIView):
    serializer_class = ParticipationsSerializer

    def get(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        experiment_name = serializer.validated_data['experiment_name']
        huscy_ids = get_participations_xml(experiment_name)

        return Response({'ids': list(huscy_ids)})


class ParticipationStatusXMLView(GenericAPIView):
    serializer_class = ParticipationStatusSerializer

    def get(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        experiment_name = serializer.validated_data['experiment_name']
        subject_ids = serializer.validated_data['subjects']

        wrapped_subject_pseudonyms = (WrappedSubject.objects.filter(subject_id__in=subject_ids)
                                                            .values_list('pseudonym', flat=True))

        result = get_participation_status_xml(experiment_name, wrapped_subject_pseudonyms)

        return Response(result)
