from http.cookies import SimpleCookie

from django.contrib.contenttypes.models import ContentType
from rest_framework import status
from rest_framework.test import APITestCase

from account.models import User
from location.models import Country
from main.models import Award, AwardType


class BaseTestCase(APITestCase):

    def setUp(self):
        self.user = User.objects.create_user(
            username='alex',
            email='alex@mail.com',
            password='alex_password',
            is_staff=True,
        )

        # get tokens
        tokens = User.create_jwt_tokens(self.user)
        self.client.cookies = SimpleCookie(
            {'access_token': tokens.get('access_token'),
             'refresh_token': tokens.get('refresh_token')})


class AwardTestCase(BaseTestCase):

    def setUp(self):
        super().setUp()

        self.country_ru = Country.objects.create(
            name={'en-GB': 'Russian'},
            code='RU',
        )

        self.content_type = ContentType.objects.get(app_label="establishment", model="establishment")

        self.award_type = AwardType.objects.create(
            country=self.country_ru,
            name="Test award type",
        )

        self.award = Award.objects.create(
            award_type=self.award_type,
            vintage_year='2017',
            state=Award.PUBLISHED,
            object_id=1,
            content_type_id=1,
        )

    def test_award_CRUD(self):
        response = self.client.get('/api/back/main/awards/', format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = {
            'award_type': self.award_type.pk,
            'state': 1,
            'object_id': 1,
            'content_type': 1,
        }

        response = self.client.post('/api/back/main/awards/', data=data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        response = self.client.get(f'/api/back/main/awards/{self.award.id}/', format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        update_data = {
            'vintage_year': '2019'
        }

        response = self.client.patch(f'/api/back/main/awards/{self.award.id}/', data=update_data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response = self.client.delete(f'/api/back/main/awards/{self.award.id}/')
        self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)


class ContentTypeTestCase(BaseTestCase):

    def setUp(self):
        super().setUp()

    def test_content_type_list(self):
        response = self.client.get('/api/back/main/content_type/', format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
