# -*- coding: utf-8 -*-
from rest_framework import generics
from rest_framework.exceptions import ValidationError

from events.rest_framework_contrib.mixins import ExternalGenericApiViewV1Mixin
from events.surveyme_integration.models import HookSubscriptionNotification
from events.surveyme_integration.api_admin.v2.serializers import HookSubscriptionNotificationResultSerializer


class IntegrationResultsView(ExternalGenericApiViewV1Mixin, generics.ListAPIView):
    queryset = HookSubscriptionNotification.objects.all()
    serializer_class = HookSubscriptionNotificationResultSerializer

    def initial(self, request, *args, **kwargs):
        self.answer_id = self.request.query_params.get('answer_id')
        self.answer_key = self.request.query_params.get('answer_key')
        if not self.answer_id and not self.answer_key:
            raise ValidationError('Answer_id or answer_key are required')
        if self.answer_id and not self.answer_id.isdigit():
            raise ValidationError('Answer_id should be int')
        return super(IntegrationResultsView, self).initial(request, *args, **kwargs)

    def get_queryset(self, *args, **kwargs):
        queryset = super().get_queryset(*args, **kwargs)
        if self.answer_id:
            queryset = queryset.filter(answer_id=self.answer_id)
        if self.answer_key:
            queryset = queryset.filter(answer__secret_code=self.answer_key)
        return queryset.filter_notifications()
