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

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


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

    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()


class ProjectEntryNode(DjangoObjectType):
    class Meta:
        model = ProjectEntry
        interfaces = (relay.Node,)


class PortfolioQuery(object):
    project = graphene.Field(ProjectNode, id=graphene.ID(), slug=graphene.String())
    projects = DjangoFilterConnectionField(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):
        return get_by_id_or_slug(Project, **kwargs)
