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

from webapp.models import Tag
from webapp.serializers import TagSerializer


from webapp.tests.tag_fixture import tagBuilder, createTagIcon


class TagsTestCase(APITestCase):
    def setUp(self):
        self.icon = createTagIcon()
        tag = tagBuilder("Party", icon=self.icon)
        self.tag_id = tag.id

        tagBuilder("Off")
        self.assertEqual(Tag.objects.count(), 2)

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

    def test_get_multiple_tags(self):
        tagBuilder("Fuksi")
        tagBuilder("Inter")

        expected = TagSerializer(
            Tag.objects.all(),
            many=True,
            context={
                "request": APIRequestFactory().get(r"http://testserver/api/events/")
            },
        ).data

        response = self.client.get("/api/tags/", format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data["results"]), 4)

        self.assertEqual(response.data["results"], expected)

    def test_get_single_tag(self):
        response = self.client.get(f"/api/tags/{self.tag_id}/", format="json")
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        serializer = TagSerializer(
            Tag.objects.get(id=self.tag_id),
            context={
                "request": APIRequestFactory().get(r"http://testserver/api/events/")
            },
        )
        self.assertEqual(response.data, serializer.data)

    def test_get_invalid_tag(self):
        response = self.client.get("/api/tags/15/", format="json")
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    # READ ONLY API! Modify result code and count
    def test_create_tag(self):
        # Authenticate
        self.client.force_authenticate(user=self.authClient)
        response = self.client.post(
            "/api/tags/",
            {
                "slug": "Test",
                "name": "Testinimi",
                "name_fi": "Testinimi",
                "name_en": "Test name",
                "icon": self.icon,
            },
            format="json",
        )

        # Method Not allowed!
        self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
        # Not created
        self.assertEqual(Tag.objects.count(), 2)
