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

from api.utils import get_object
from notes.models import InstrumentBookmark
from notes.schema import InstrumentBookmarkNode
from .models import BasicKnowledge


class InstrumentNode(DjangoObjectType):
    bookmarks = graphene.List(InstrumentBookmarkNode)

    class Meta:
        model = BasicKnowledge
        filter_fields = ['slug', 'type']
        interfaces = (relay.Node,)
        only_fields = [
            'slug', 'title', 'intro', 'type', 'contents',
        ]

    def resolve_bookmarks(self, info, **kwargs):
        return InstrumentBookmark.objects.filter(
            user=info.context.user,
            instrument=self
        )

class BasicKnowledgeQuery(object):
    instrument = graphene.Field(InstrumentNode, slug=graphene.String(), id=graphene.ID())
    instruments = DjangoFilterConnectionField(InstrumentNode)

    def resolve_instrument(self, info, **kwargs):
        slug = kwargs.get('slug')
        instrument_id = kwargs.get('id')

        if instrument_id is not None:
            return get_object(BasicKnowledge, instrument_id)
        if slug is not None:
            return BasicKnowledge.objects.get(slug=slug)
        return None

    def resolve_instruments(self, info, **kwargs):
        return BasicKnowledge.objects.all().live()
