from http.cookies import SimpleCookie

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase

from account.models import User
from authorization.tests.tests_authorization import get_tokens_for_user


class AccountUserTests(APITestCase):
    def setUp(self):
        self.data = get_tokens_for_user()

    def test_user_url(self):
        url = reverse('web:account:user-retrieve-update')
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.cookies = SimpleCookie(
            {'access_token': self.data['tokens'].get('access_token'),
             'refresh_token': self.data['tokens'].get('access_token')})

        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data = {
            "username": self.data["username"],
            "first_name": "Test first name",
            "last_name": "Test last name",
            "cropped_image_url": "http://localhost/image/cropped.png",
            "image_url": "http://localhost/image/avatar.png",
            "email": "sedragurdatest@desoz.com",
            "newsletter": self.data["newsletter"]
        }
        response = self.client.patch(url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        data["email"] = "sedragurdatest2@desoz.com"

        response = self.client.put(url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)


class AccountChangePasswordTests(APITestCase):
    def setUp(self):
        self.data = get_tokens_for_user()

    def test_change_password(self):
        data = {
            "old_password": self.data["password"],
            "password": "new password"
        }
        url = reverse('web:account:change-password')

        response = self.client.patch(url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

        self.client.cookies = SimpleCookie(
            {'access_token': self.data['tokens'].get('access_token'),
             'refresh_token': self.data['tokens'].get('access_token')})

        response = self.client.patch(url, data=data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)


class AccountConfirmEmail(APITestCase):
    def setUp(self):
        self.data = get_tokens_for_user()

    def test_confirm_email(self):
        user = User.objects.get(email=self.data["email"])
        token = user.confirm_email_token
        uidb64 = user.get_user_uidb64
        url = reverse('web:account:confirm-email', kwargs={
            'uidb64': uidb64,
            'token': token
        })
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK)
