from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase, APIRequestFactory

from webapp.models import Feed
from webapp.serializers import FeedSerializer
from webapp.tests.tag_fixture import tagBuilder


class FeedTestCase(APITestCase):

    def setUp(self):
        tag1 = tagBuilder()
        tag2 = tagBuilder("testtag2")

        feed = Feed.objects.create(title="TestFeed", visible=True, description="diidadaapa", content="lorem ipsum")
        feed.tags.add(tag1)
        feed.tags.add(tag2)
        self.assertEqual(Feed.objects.count(), 1)
        self.assertEqual(Feed.objects.all()[0].tags.count(), 2)

        username, password = "test_admin", "password123"
        self.authClient = User.objects.create_superuser(username, "myemail@test.com", password)

    def test_get_feed(self):
        response = self.client.get("/api/feed/", format="json")
        self.assertTrue(status.is_success(response.status_code))

        feeds = Feed.objects.all()
        serializer = FeedSerializer(
            feeds, many=True,
            context={
                "request": APIRequestFactory().get(r"http://testserver/api/events/")
            })
        self.assertEqual(response.data["results"], serializer.data)

    def test_post_feed(self):
        tag1_id = tagBuilder("test1").id
        tag2_id = tagBuilder("test2").id

        data = {
            "tag_id": [tag1_id, tag2_id],
            "title_fi": "testtitle",
            "title_en": "testtitle",
            "visible": "True",
            "description_fi": "liirumlaarum",
            "description_en": "liirumlaarum",
            "content_fi": "lorem ipsum",
            "content_en": "lorem ipsum"
        }
        # Try post without authentication
        response = self.client.post("/api/feed/", data, format="json")
        self.assertTrue(response.status_code, status.HTTP_401_UNAUTHORIZED)
        self.assertEqual(Feed.objects.count(), 1)
        # Authenticate
        self.client.force_authenticate(user=self.authClient)
        response = self.client.post("/api/feed/", data, format="json")
        # Return success and check object was created
        self.assertTrue(response.status_code, status.HTTP_201_CREATED)
        self.assertEqual(Feed.objects.count(), 2)

        created = Feed.objects.get(title_fi="testtitle")
        self.assertEqual(created.tags.count(), 2)
