from django.core import mail
from django.test import TransactionTestCase as TestCase
from django.urls import reverse
from django.utils.translation import gettext as _

from registration.models import RegistrationProfile

from newsreader.accounts.tests.factories import RegistrationProfileFactory, UserFactory


class ResendActivationTestCase(TestCase):
    def setUp(self):
        self.url = reverse("accounts:activate-resend")
        self.success_url = reverse("accounts:activate-complete")
        self.register_url = reverse("accounts:register")

    def test_simple(self):
        response = self.client.get(self.url)

        self.assertEquals(response.status_code, 200)

    def test_resent_form(self):
        data = {
            "email": "test@test.com",
            "password1": "test12456",
            "password2": "test12456",
        }

        response = self.client.post(self.register_url, data)

        register_profile = RegistrationProfile.objects.get()
        original_kwargs = {"activation_key": register_profile.activation_key}

        response = self.client.post(self.url, {"email": "test@test.com"})

        self.assertContains(response, _("We have sent an email to"))

        self.assertEquals(len(mail.outbox), 2)

        register_profile.refresh_from_db()

        kwargs = {"activation_key": register_profile.activation_key}
        response = self.client.get(reverse("accounts:activate", kwargs=kwargs))

        self.assertRedirects(response, self.success_url)

        register_profile.refresh_from_db()
        user = register_profile.user

        self.assertEquals(user.is_active, True)

        # test the old activation code
        response = self.client.get(reverse("accounts:activate", kwargs=original_kwargs))

        self.assertEquals(response.status_code, 200)
        self.assertContains(response, _("Account activation failed"))

    def test_existing_account(self):
        user = UserFactory(is_active=True)
        profile = RegistrationProfileFactory(user=user, activated=True)

        response = self.client.post(self.url, {"email": user.email})
        self.assertEquals(response.status_code, 200)

        # default behaviour is to show success page but not send an email
        self.assertContains(response, _("We have sent an email to"))

        self.assertEquals(len(mail.outbox), 0)

    def test_no_account(self):
        response = self.client.post(self.url, {"email": "fake@mail.com"})
        self.assertEquals(response.status_code, 200)

        # default behaviour is to show success page but not send an email
        self.assertContains(response, _("We have sent an email to"))

        self.assertEquals(len(mail.outbox), 0)
