import graphene
from django.db.models import Q
from graphene import relay
from graphene_django import DjangoObjectType

from api.utils import get_by_id_or_slug
from portfolio.models import Project, ProjectEntry
from users.models import Role, UserRole, User


class ProjectEntryNode(DjangoObjectType):
    class Meta:
        model = ProjectEntry
        interfaces = (relay.Node,)
        fields = ('description', 'document_url', 'project', 'created')


class ProjectNode(DjangoObjectType):
    pk = graphene.Int()
    entries_count = graphene.Int()
    entries = graphene.List(ProjectEntryNode)

    class Meta:
        model = Project
        filter_fields = ['slug', 'appearance']
        interfaces = (relay.Node,)

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

    def resolve_entries_count(self, *args, **kwargs):
        return self.entries.count()

    @staticmethod
    def resolve_entries(root: Project, info, **kwargs):
        return root.entries.all()


class PortfolioQuery(object):
    project = graphene.Field(ProjectNode, id=graphene.ID(), slug=graphene.String())
    projects = graphene.List(ProjectNode)

    def resolve_projects(self, info, **kwargs):
        user = info.context.user
        if user.is_superuser:
            return Project.objects.all().order_by('-pk')

        if UserRole.get_role_for_user(user).role == Role.objects.get_default_teacher_role():
            return Project.objects.filter(Q(student__school_classes__in=user.school_classes.all(), final=True) |
                                          Q(student=user, final=False)).distinct()

        return Project.objects.filter(student=user)

    def resolve_project(self, info, **kwargs):
        user = info.context.user # type: User
        project = get_by_id_or_slug(Project, **kwargs) #type: Project

        if project.is_viewable_by(user):
            return project
        return None
