from django.contrib.auth import get_user_model
from django.db import models
from django_extensions.db.models import TitleSlugDescriptionModel
from wagtail.core.fields import StreamField

from books.blocks import DocumentBlock, ImageUrlBlock, LinkBlock, VideoBlock
from books.models import TextBlock
from users.models import SchoolClass


class Room(TitleSlugDescriptionModel):
    class Meta:
        verbose_name = 'Raum'
        verbose_name_plural = 'Räume'

    school_class = models.ForeignKey(SchoolClass, blank=False, null=False, on_delete=models.CASCADE,
                                     related_name='rooms')
    appearance = models.CharField(blank=True, null=False, max_length=255)
    user_created = models.BooleanField(blank=False, null=False, default=True)
    restricted = models.BooleanField(default=False)

    def __str__(self):
        return f'{self.title} - {self.school_class}'


class RoomEntry(TitleSlugDescriptionModel):
    class Meta:
        verbose_name = 'Raumeintrag'
        verbose_name_plural = 'Raumeinträge'

    room = models.ForeignKey(Room, blank=False, null=False, on_delete=models.CASCADE, related_name='room_entries')
    author = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE)

    contents = StreamField([
        ('text_block', TextBlock()),
        ('image_url_block', ImageUrlBlock()),
        ('link_block', LinkBlock()),
        ('document_block', DocumentBlock()),
        ('video_block', VideoBlock())
    ], null=True, blank=True)

    def __str__(self):
        return f'RoomEntry {self.id}-{self.title}-{self.author}'

    def can_user_see_entry(self, user):
        return user.is_superuser or self.room.school_class.is_user_in_schoolclass(user)


class ModuleRoomSlug(TitleSlugDescriptionModel):
    class Meta:
        verbose_name = 'Slug für Modul-Raum'
        verbose_name_plural = 'Slugs für Modul-Raum'

    def __str__(self):
        return f'ModuleRoomSlug {self.id}-{self.title}'


class Comment(models.Model):
    text = models.TextField()
    room_entry = models.ForeignKey(RoomEntry, related_name='comments', on_delete=models.PROTECT)
    owner = models.ForeignKey(get_user_model(), related_name='comments', on_delete=models.PROTECT)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.text
