from django.contrib.auth import get_user_model
from django.db import models
from django_extensions.db.models import TitleSlugDescriptionModel
from graphql_relay import to_global_id

from users.models import User


class GraphqlNodeMixin:
    def default_node_name(self):
        return f'{self.__class__.__name__}Node'

    @property
    def graphql_id(self):
        return to_global_id(self.default_node_name(), self.id)

class Project(TitleSlugDescriptionModel, GraphqlNodeMixin):
    objectives = models.TextField(blank=True)
    appearance = models.CharField(blank=True, null=False, max_length=255)
    student = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='projects')
    final = models.BooleanField(default=False)
    school_class = models.ForeignKey('users.SchoolClass', null=True, default=None, on_delete=models.SET_NULL)

    def __str__(self):
        return self.title

    def is_viewable_by(self, user: User):
        return user.id == self.student.id or (
            self.final and self.student.get_teacher().id == user.id
        )

class ProjectEntry(models.Model):
    activity = models.TextField(blank=True)
    reflection = models.TextField(blank=True)
    next_steps = models.TextField(blank=True)
    document_url = models.TextField(blank=True)
    description = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)
    project = models.ForeignKey(Project, related_name='entries', on_delete=models.CASCADE)

    def __str__(self):
        return self.description
