from django.db import models
from django.utils import timezone
from django.utils.translation import gettext as _

from newsreader.core.models import TimeStampedModel
from newsreader.news.collection.models import CollectionRule


class Post(TimeStampedModel):
    title = models.CharField(max_length=200, blank=True, null=True)
    body = models.TextField(blank=True)
    author = models.CharField(max_length=40, blank=True, null=True)
    publication_date = models.DateTimeField(default=timezone.now)
    url = models.URLField(max_length=1024, blank=True, null=True)

    read = models.BooleanField(default=False)
    saved = models.BooleanField(default=False)

    rule = models.ForeignKey(
        CollectionRule, on_delete=models.CASCADE, editable=False, related_name="posts"
    )
    remote_identifier = models.CharField(
        max_length=500, editable=False, blank=True, null=True
    )

    def __str__(self):
        return "Post-{}".format(self.pk)


class Category(TimeStampedModel):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(
        "accounts.User",
        verbose_name=_("Owner"),
        related_name="categories",
        on_delete=models.CASCADE,
    )

    @property
    def rule_ids(self):
        return self.rules.values_list("pk", flat=True)

    class Meta:
        verbose_name = _("Category")
        verbose_name_plural = _("Categories")
        unique_together = ("name", "user")

    def __str__(self):
        return self.name
