from django.db import models
from django.urls import reverse
from django.utils.translation import gettext as _

from newsreader.core.models import TimeStampedModel
from newsreader.news.collection.choices import RuleTypeChoices


class CollectionRuleQuerySet(models.QuerySet):
    def enabled(self):
        return self.filter(enabled=True)


class CollectionRule(TimeStampedModel):
    name = models.CharField(max_length=100)
    type = models.CharField(
        max_length=20, choices=RuleTypeChoices.choices, default=RuleTypeChoices.feed
    )

    url = models.URLField(max_length=1024)
    website_url = models.URLField(
        max_length=1024, editable=False, blank=True, null=True
    )
    favicon = models.URLField(blank=True, null=True)

    category = models.ForeignKey(
        "core.Category",
        blank=True,
        null=True,
        verbose_name=_("Category"),
        related_name="rules",
        help_text=_("Posts from this rule will be tagged with this category"),
        on_delete=models.SET_NULL,
    )

    last_run = models.DateTimeField(blank=True, null=True)
    succeeded = models.BooleanField(default=False)
    error = models.CharField(max_length=1024, blank=True, null=True)

    enabled = models.BooleanField(
        default=True, help_text=_("Wether or not to collect items from this feed")
    )

    user = models.ForeignKey(
        "accounts.User",
        verbose_name=_("Owner"),
        related_name="rules",
        on_delete=models.CASCADE,
    )

    objects = CollectionRuleQuerySet.as_manager()

    def __str__(self):
        return self.name

    @property
    def update_url(self):
        return reverse("news:collection:feed-update", kwargs={"pk": self.pk})

    @property
    def source_url(self):
        return self.url

    @property
    def failed(self):
        return not self.succeeded and self.last_run
