from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.utils.translation import gettext_lazy as _

from .test_utils import create_election

User = get_user_model()


class UserTests(TestCase):
    def setUp(self):
        self.election_1 = create_election(1)
        self.election_2 = create_election(2)
        self.election_3 = create_election(3, False)

        self.cas_user = User.objects.create(
            username="cas__user", email="user@clipper.ens.fr", full_name="Ulric Ser"
        )

        self.user_1 = User.objects.create(
            username="1__user",
            email="user1@ens.fr",
            full_name="Ulric Ser",
            election=self.election_1,
        )

        self.pwd_user = User.objects.create(
            username="pwd__user", email="user@ens.fr", full_name="Ulric Ser"
        )

    def test_special_user(self):
        self.assertTrue(self.user_1.can_vote(self.client, self.election_1))
        self.assertFalse(self.user_1.can_vote(self.client, self.election_2))
        self.assertFalse(self.user_1.can_vote(self.client, self.election_3))

    def test_cas_user(self):
        # On simule la connection par CAS via authens
        session = self.client.session
        session["CASCONNECTED"] = True
        session.save()

        # On sauvegarde le cookie de session
        session_cookie_name = settings.SESSION_COOKIE_NAME
        self.client.cookies[session_cookie_name] = session.session_key

        self.assertFalse(self.cas_user.can_vote(self.client, self.election_1))
        self.assertTrue(self.cas_user.can_vote(self.client, self.election_3))

    def test_pwd_user(self):
        self.assertFalse(self.pwd_user.can_vote(self.client, self.election_1))
        self.assertFalse(self.pwd_user.can_vote(self.client, self.election_2))

    def test_connection_method(self):
        self.assertEqual(self.cas_user.connection_method, _("CAS"))
        self.assertEqual(self.pwd_user.connection_method, _("mot de passe"))
        self.assertEqual(self.user_1.connection_method, _("identifiants spécifiques"))
