from django.conf import settings
from django.db import models
from django.utils import timezone

from library.models import Project


class Announcement(models.Model):
    """A staff-written, site-wide announcement (global). Kept forever."""
    title = models.CharField(max_length=200)
    body = models.TextField(blank=True, default='')  # Markdown
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name='announcements',
    )
    published = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at', '-pk']

    def __str__(self):
        return self.title

    @property
    def comment_count(self):
        return self.comments.count()


class AnnouncementRead(models.Model):
    """Read receipt: one row per (announcement, user) the first time it's opened."""
    announcement = models.ForeignKey(
        Announcement, on_delete=models.CASCADE, related_name='reads',
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='announcement_reads',
    )
    read_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['announcement', 'user'], name='uniq_announcement_read',
            ),
        ]

    def __str__(self):
        return f'{self.user.username} read {self.announcement.title}'


class AnnouncementComment(models.Model):
    """A comment on an announcement page. Body is Markdown."""
    announcement = models.ForeignKey(
        Announcement, on_delete=models.CASCADE, related_name='comments',
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='announcement_comments',
    )
    body = models.TextField()
    created_at = models.DateTimeField(default=timezone.now)
    updated_at = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ['created_at', 'pk']

    def save(self, *args, **kwargs):
        if self._state.adding:
            now = timezone.now()
            self.created_at = now
            self.updated_at = now
        else:
            self.updated_at = timezone.now()
        super().save(*args, **kwargs)

    def __str__(self):
        return f'{self.user.username}: {self.body[:40]}'


class Notification(models.Model):
    """A personal alert triggered by UGC activity. Retained at ~200 per user."""
    KIND_CHOICES = [
        ('version', 'New version'),
        ('asset', 'New media'),
        ('edit', 'Project edited'),
        ('comment', 'New comment'),
    ]
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='notifications',
    )
    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='+',
    )
    project = models.ForeignKey(
        Project, on_delete=models.CASCADE, related_name='notifications',
    )
    kind = models.CharField(max_length=16, choices=KIND_CHOICES)
    text = models.CharField(max_length=255)
    read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at', '-pk']

    def __str__(self):
        return f'{self.user.username}: {self.text}'
