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

import pytz

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)

    timezone = models.CharField(
        choices=((timezone, timezone) for timezone in pytz.all_timezones),
        max_length=100,
        default=str(pytz.utc),
    )

    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,
    )

    # Reddit
    reddit_allow_nfsw = models.BooleanField(_("Allow NSFW posts"), default=False)
    reddit_allow_spoiler = models.BooleanField(_("Allow spoilers"), default=False)
    reddit_allow_viewed = models.BooleanField(
        _("Allow already seen posts"), default=True
    )
    reddit_upvotes_min = models.PositiveIntegerField(
        _("Minimum amount of upvotes"), default=0
    )
    reddit_downvotes_max = models.PositiveIntegerField(
        _("Maximum amount of downvotes"), blank=True, null=True
    )
    reddit_comments_min = models.PositiveIntegerField(
        _("Minimum amount of comments"), default=0
    )

    # Twitter
    screen_name = models.CharField(max_length=255, blank=True, null=True)

    objects = CollectionRuleQuerySet.as_manager()

    def __str__(self):
        return self.name

    @property
    def update_url(self):
        if self.type == RuleTypeChoices.subreddit:
            return reverse("news:collection:subreddit-update", kwargs={"pk": self.pk})
        elif self.type == RuleTypeChoices.twitter_timeline:
            return reverse(
                "news:collection:twitter-timeline-update", kwargs={"pk": self.pk}
            )

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

    @property
    def source_url(self):
        if self.type == RuleTypeChoices.subreddit:
            from newsreader.news.collection.reddit import REDDIT_API_URL, REDDIT_URL

            return self.url.replace(REDDIT_API_URL, REDDIT_URL)
        elif self.type == RuleTypeChoices.twitter_timeline:
            from newsreader.news.collection.twitter import TWITTER_URL

            return f"{TWITTER_URL}/{self.screen_name}"

        return self.url

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