import pytz
from datetime import datetime, timedelta

from rest_framework.test import APITestCase
from rest_framework import status
from http.cookies import SimpleCookie

from account.models import User
from news.models import News, NewsType

from establishment.models import Establishment, EstablishmentType, Employee
from location.models import Country


class BaseTestCase(APITestCase):

    def setUp(self):

        self.username = 'sedragurda'
        self.password = 'sedragurdaredips19'
        self.email = 'sedragurda@desoz.com'
        self.newsletter = True
        self.user = User.objects.create_user(
            username=self.username, email=self.email, password=self.password)

        # get tokkens
        tokkens = User.create_jwt_tokens(self.user)
        self.client.cookies = SimpleCookie(
            {'access_token': tokkens.get('access_token'),
             'refresh_token': tokkens.get('refresh_token'),
             'locale': "en-GB"
             })


class TranslateFieldTests(BaseTestCase):

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

        self.news_type = NewsType.objects.create(name="Test news type")
        self.news_type.save()

        self.country_ru, created = Country.objects.get_or_create(
            name={"en-GB": "Russian"}
        )

        self.news_item = News.objects.create(
            id=8,
            created_by=self.user,
            modified_by=self.user,
            title={
                "en-GB": "Test news item",
                "ru-RU": "Тестовая новость"
            },
            description={"en-GB": "Test description"},
            end=datetime.now(pytz.utc) + timedelta(hours=13),
            news_type=self.news_type,
            slugs={'en-GB': 'test'},
            state=News.PUBLISHED,
            country=self.country_ru,
        )
        self.slug = next(iter(self.news_item.slugs.values()))
        self.news_item.save()

    def test_model_field(self):
        self.assertTrue(hasattr(self.news_item, "title_translated"))

    def test_read_locale(self):
        response = self.client.get(f"/api/web/news/slug/{self.slug}/", format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        news_data = response.json()
        self.assertIn("title_translated", news_data)

        self.assertIn("Test news item", news_data['title_translated'])


class BaseAttributeTests(BaseTestCase):

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

        self.establishment_type = EstablishmentType.objects.create(name="Test establishment type")
        self.establishment = Establishment.objects.create(
            name="Test establishment",
            establishment_type_id=self.establishment_type.id,
            is_publish=True
        )

    def test_base_attr_api(self):
        data = {
            'user': self.user.id,
            'name': 'Test name'
        }

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

        response_data = response.json()
        self.assertIn("id", response_data)
        self.assertIsInstance(response_data['id'], int)

        employee = Employee.objects.get(id=response_data['id'])

        self.assertEqual(self.user, employee.created_by)
        self.assertEqual(self.user, employee.modified_by)

        modify_user = User.objects.create_user(
            username='sedragurda2',
            password='sedragurdaredips192',
            email='sedragurda2@desoz.com',
        )

        modify_tokkens = User.create_jwt_tokens(modify_user)
        self.client.cookies = SimpleCookie(
            {'access_token': modify_tokkens.get('access_token'),
             'refresh_token': modify_tokkens.get('refresh_token'),
             'locale': "en"
             })

        update_data = {
            'name': 'Test new name'
        }

        response = self.client.patch(f'/api/back/establishments/employees/{employee.pk}/', data=update_data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        employee.refresh_from_db()
        self.assertEqual(modify_user, employee.modified_by)
        self.assertEqual(self.user, employee.created_by)
