import graphene
from graphene import relay

from api.utils import get_object
from books.models import Topic
from books.schema.nodes import TopicNode


class UpdateLastTopic(relay.ClientIDMutation):
    class Input:
        # todo: use slug here too
        id = graphene.ID()

    topic = graphene.Field(TopicNode)

    @classmethod
    def mutate_and_get_payload(cls, root, info, **args):
        user = info.context.user
        id = args.get('id')

        topic = get_object(Topic, id)
        if not topic:
            raise Topic.DoesNotExist

        user.last_topic = topic
        user.save()

        return cls(topic=topic)
