from django.contrib.auth import get_user_model
from django.db import models
from django_extensions.db.models import TimeStampedModel
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.core.fields import RichTextField
from wagtail.snippets.models import register_snippet
from wagtailautocomplete.edit_handlers import AutocompletePanel

from core.constants import DEFAULT_RICH_TEXT_FEATURES


@register_snippet
class Assignment(TimeStampedModel):
    title = models.CharField(max_length=255)
    assignment = models.TextField()
    solution = RichTextField(null=True, blank=True, features=DEFAULT_RICH_TEXT_FEATURES)
    deleted = models.BooleanField(default=False)
    owner = models.ForeignKey(get_user_model(),
                              on_delete=models.PROTECT, null=True,
                              blank=True)  # probably don't want to delete all assignments if a user gets deleted
    module = models.ForeignKey('books.Module', related_name='assignments', on_delete=models.CASCADE)
    user_created = models.BooleanField(default=False)
    taskbase_id = models.CharField(max_length=255, null=True, blank=True)

    panels = [
        FieldPanel('title'),
        FieldPanel('assignment'),
        FieldPanel('solution'),
        FieldPanel('module'),
        AutocompletePanel('owner')
    ]

    def __str__(self):
        return self.title if not self.user_created else '{} (erstellt von {})'.format(self.title, self.owner)


class StudentSubmission(TimeStampedModel):
    text = models.TextField(blank=True)
    document = models.URLField(blank=True, default='', max_length=255)
    assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, related_name='submissions')
    student = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='submissions')
    final = models.BooleanField(default=False)

    def __str__(self):
        return '{} - {}'.format(self.student.full_name, self.text)


class SubmissionFeedback(TimeStampedModel):
    text = models.TextField(blank=True)
    teacher = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='feedbacks')
    student_submission = models.OneToOneField(StudentSubmission, on_delete=models.CASCADE, primary_key=True,
                                              related_name='submission_feedback')
    final = models.BooleanField(default=False)

    def __str__(self):
        return '{} - {}'.format(self.student_submission.student.full_name, self.text)
