from django.urls import reverse

from newsreader.accounts.tests.factories import UserFactory
from newsreader.news.collection.models import CollectionRule
from newsreader.news.collection.tests.factories import CollectionRuleFactory
from newsreader.news.core.tests.factories import CategoryFactory


class CollectionRuleViewTestCase:
    def setUp(self):
        self.user = UserFactory(password="test")
        self.client.force_login(self.user)

        self.category = CategoryFactory(user=self.user)
        self.form_data = {"name": "", "category": "", "url": "", "timezone": ""}

    def test_simple(self):
        response = self.client.get(self.url)

        self.assertEquals(response.status_code, 200)

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

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

        rule = CollectionRule.objects.get()

        self.assertEquals(rule.category, None)

    def test_categories_only_from_user(self):
        other_user = UserFactory()
        other_categories = CategoryFactory.create_batch(size=4, user=other_user)

        response = self.client.get(self.url)

        for category in other_categories:
            self.assertNotContains(response, category.name)

    def test_category_of_other_user(self):
        other_user = UserFactory()
        other_rule = CollectionRuleFactory(name="other rule", user=other_user)

        self.form_data.update(
            name="new name",
            category=other_rule.category,
            url=other_rule.url,
        )

        other_url = reverse("news:collection:feed-update", args=[other_rule.pk])
        response = self.client.post(other_url, self.form_data)

        self.assertEquals(response.status_code, 404)

        other_rule.refresh_from_db()

        self.assertEquals(other_rule.name, "other rule")

    def test_with_other_user_rules(self):
        other_user = UserFactory()
        other_categories = CategoryFactory.create_batch(size=4, user=other_user)

        self.form_data.update(category=other_categories[2].pk)

        response = self.client.post(self.url, self.form_data)

        self.assertContains(response, "not one of the available choices")
