import graphene
from graphene import relay
from graphene_django import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField

from api.utils import get_by_id
from surveys.models import Answer
from .models import Survey


class AnswerNode(DjangoObjectType):
    pk = graphene.Int()

    class Meta:
        model = Answer
        interfaces = (relay.Node,)
        filter_fields = []

    def resolve_pk(self, *args, **kwargs):
        return self.id


class SurveyNode(DjangoObjectType):
    pk = graphene.Int()
    answer = graphene.Field(AnswerNode)

    class Meta:
        model = Survey
        filter_fields = []
        interfaces = (relay.Node,)

    def resolve_pk(self, *args, **kwargs):
        return self.id

    def resolve_answer(self, info, **kwargs):
        user = info.context.user
        try:
            return Answer.objects.get(owner=user, survey=self)
        except Answer.DoesNotExist:
            return None

class SurveysQuery(object):
    survey = graphene.Field(SurveyNode, id=graphene.ID())
    surveys = DjangoFilterConnectionField(SurveyNode)

    def resolve_surveys(self, info, **kwargs):
        return Survey.objects.all()

    def resolve_survey(self, info, **kwargs):
        return get_by_id(Survey, **kwargs)
