from django.test import TestCase
from django.urls import reverse

from django_celery_beat.models import PeriodicTask

from newsreader.news.collection.choices import RuleTypeChoices
from newsreader.news.collection.models import CollectionRule
from newsreader.news.collection.tests.factories import FeedFactory
from newsreader.news.collection.tests.views.base import CollectionRuleViewTestCase
from newsreader.news.core.tests.factories import CategoryFactory


class FeedCreateViewTestCase(CollectionRuleViewTestCase, TestCase):
    def setUp(self):
        super().setUp()

        self.url = reverse("news:collection:feed-create")

        self.form_data.update(
            name="new rule",
            url="https://www.rss.com/rss",
            category=str(self.category.pk),
        )

    def test_creation(self):
        response = self.client.post(self.url, self.form_data)

        self.assertEqual(response.status_code, 302)

        rule = CollectionRule.objects.get(name="new rule")

        self.assertEqual(rule.type, RuleTypeChoices.feed)
        self.assertEqual(rule.url, "https://www.rss.com/rss")
        self.assertEqual(rule.favicon, None)
        self.assertEqual(rule.category.pk, self.category.pk)
        self.assertEqual(rule.user.pk, self.user.pk)

        self.assertTrue(
            PeriodicTask.objects.get(
                name=f"{self.user.email}-feed", task="FeedTask", enabled=True
            )
        )


class FeedUpdateViewTestCase(CollectionRuleViewTestCase, TestCase):
    def setUp(self):
        super().setUp()

        self.rule = FeedFactory(
            name="collection rule", user=self.user, category=self.category
        )
        self.url = reverse("news:collection:feed-update", kwargs={"pk": self.rule.pk})

        self.form_data.update(
            name=self.rule.name,
            category=self.rule.category.pk,
            url=self.rule.url,
        )

    def test_name_change(self):
        self.form_data.update(name="new name")

        response = self.client.post(self.url, self.form_data)
        self.assertEqual(response.status_code, 302)

        self.rule.refresh_from_db()

        self.assertEqual(self.rule.name, "new name")

    def test_category_change(self):
        new_category = CategoryFactory(user=self.user)

        self.form_data.update(category=new_category.pk)

        response = self.client.post(self.url, self.form_data)
        self.assertEqual(response.status_code, 302)

        self.rule.refresh_from_db()

        self.assertEqual(self.rule.category.pk, new_category.pk)

    def test_category_removal(self):
        self.form_data.update(category="")

        response = self.client.post(self.url, self.form_data)
        self.assertEqual(response.status_code, 302)

        self.rule.refresh_from_db()

        self.assertEqual(self.rule.category, None)
