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

from api.utils import get_object
from core.logger import get_logger
from .connections import TopicConnection, ModuleConnection
from .nodes import ContentBlockNode, ChapterNode, ModuleNode, TopicNode, SnapshotNode
from ..models import Book, Topic, Module, Chapter, Snapshot

logger = get_logger(__name__)


class BookQuery(object):
    node = relay.Node.Field()
    topic = graphene.Field(TopicNode, slug=graphene.String())
    module = graphene.Field(ModuleNode, slug=graphene.String(), id=graphene.ID())
    chapter = relay.Node.Field(ChapterNode)
    content_block = relay.Node.Field(ContentBlockNode)
    snapshot = relay.Node.Field(SnapshotNode)

    topics = relay.ConnectionField(TopicConnection)
    modules = relay.ConnectionField(ModuleConnection)
    chapters = DjangoFilterConnectionField(ChapterNode)

    def resolve_books(self, *args, **kwargs):
        return Book.objects.filter(**kwargs).live()

    def resolve_topics(self, *args, **kwargs):
        return Topic.objects.live()

    def resolve_modules(self, *args, **kwargs):
        return Module.objects.filter(**kwargs).live()

    def resolve_chapters(self, *args, **kwargs):
        return Chapter.objects.filter(**kwargs).live()

    def resolve_snapshot(self, info, **kwargs):
        id = kwargs.get('id')
        snapshot = get_object(Snapshot, id)
        return snapshot

    def resolve_module(self, info, **kwargs):
        slug = kwargs.get('slug')
        id = kwargs.get('id')
        module = None
        try:
            if id is not None:
                module = get_object(Module, id)

            elif slug is not None:
                module = Module.objects.get(slug=slug)

            return module

        except Module.DoesNotExist:
            return None

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

        if id is not None:
            return get_object(Topic, id)
        if slug is not None:
            return Topic.objects.get(slug=slug)
        return None
