from datetime import date
from unittest import mock

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.test import Client, TestCase
from django.urls import reverse, reverse_lazy

from bds.models import BDSProfile

User = get_user_model()


def give_bds_buro_permissions(user: User) -> None:
    perm = Permission.objects.get(content_type__app_label="bds", codename="is_team")
    user.user_permissions.add(perm)


def login_url(next=None):
    login_url = reverse_lazy(settings.LOGIN_URL)
    if next is None:
        return login_url
    else:
        return "{}?next={}".format(login_url, next)


class TestHomeView(TestCase):
    @mock.patch("gestioncof.signals.messages")
    def test_get(self, _):
        user = User.objects.create_user(username="random_user")
        give_bds_buro_permissions(user)
        self.client.force_login(
            user, backend="django.contrib.auth.backends.ModelBackend"
        )
        resp = self.client.get(reverse("bds:home"))
        self.assertEqual(resp.status_code, 200)


class TestRegistrationView(TestCase):
    @mock.patch("gestioncof.signals.messages")
    def test_get_autocomplete(self, _):
        user = User.objects.create_user(username="toto")
        url = reverse("bds:autocomplete") + "?q=foo"
        client = Client()

        # Anonymous GET
        resp = client.get(url)
        self.assertRedirects(resp, login_url(next=url))

        # Logged-in but unprivileged GET
        client.force_login(user, backend="django.contrib.auth.backends.ModelBackend")
        resp = client.get(url)
        self.assertEqual(resp.status_code, 403)

        # Burô user GET
        give_bds_buro_permissions(user)
        resp = client.get(url)
        self.assertEqual(resp.status_code, 200)

    @mock.patch("gestioncof.signals.messages")
    def test_get(self, _):
        user = User.objects.create_user(username="toto")
        url = reverse("bds:user.update", args=(user.id,))
        client = Client()

        # Anonymous GET
        resp = client.get(url)
        self.assertRedirects(resp, login_url(next=url))

        # Logged-in but unprivileged GET
        client.force_login(user, backend="django.contrib.auth.backends.ModelBackend")
        resp = client.get(url)
        self.assertEqual(resp.status_code, 403)

        # Burô user GET
        give_bds_buro_permissions(user)
        resp = client.get(url)
        self.assertEqual(resp.status_code, 200)


class TestResetMemberships(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.admin = User.objects.create_user(username="bds_admin")

        # Create users and profiles
        cls.u_1 = User.objects.create_user(username="bds-01")
        cls.p_1 = BDSProfile.objects.create(user=cls.u_1)

        cls.u_2 = User.objects.create_user(username="bds-02")
        cls.p_2 = BDSProfile.objects.create(user=cls.u_2)

        cls.u_3 = User.objects.create_user(username="bds-03")
        cls.p_3 = BDSProfile.objects.create(user=cls.u_3)

        cls.u_4 = User.objects.create_user(username="bds-04")
        cls.p_4 = BDSProfile.objects.create(user=cls.u_4)

    @mock.patch("gestioncof.signals.messages")
    def setUp(self, _):
        give_bds_buro_permissions(self.admin)
        # bds-01 est membre à l'année
        self.p_1.is_member = True
        self.p_1.mails_bds = True
        self.p_1.cotisation_period = "ANN"
        self.p_1.save()

        # bds-02 est membre au S1
        self.p_2.is_member = True
        self.p_2.mails_bds = True
        self.p_2.cotisation_period = "SE1"
        self.p_2.save()

        # bds-03 est membre au S2
        self.p_3.is_member = True
        self.p_3.mails_bds = True
        self.p_3.cotisation_period = "SE2"
        self.p_3.save()

    @mock.patch("gestioncof.signals.messages")
    def test_get_expired(self, _):
        user = User.objects.create_user(username="toto")
        url = reverse("bds:members.expired")
        client = Client()

        # Anonymous GET
        resp = client.get(url)
        self.assertRedirects(resp, login_url(next=url))

        # Logged-in but unprivileged GET
        client.force_login(user, backend="django.contrib.auth.backends.ModelBackend")
        resp = client.get(url)
        self.assertEquals(resp.status_code, 403)

        # Burô user GET
        give_bds_buro_permissions(user)
        resp = client.get(url)
        self.assertEquals(resp.status_code, 200)

        self.assertQuerysetEqual(
            resp.context_data["object_list"], BDSProfile.expired_members()
        )

    @mock.patch("gestioncof.signals.messages")
    def test_get_reset(self, _):
        user = User.objects.create_user(username="tata")
        url = reverse("bds:members.reset")
        client = Client()

        # Anonymous GET
        resp = client.get(url)
        self.assertRedirects(resp, login_url(next=url))

        # Logged-in but unprivileged GET
        client.force_login(user, backend="django.contrib.auth.backends.ModelBackend")
        resp = client.get(url)
        self.assertEquals(resp.status_code, 403)

        # Burô user GET
        give_bds_buro_permissions(user)
        resp = client.get(url)
        self.assertRedirects(resp, reverse("bds:members.expired"))

    def test_expired_memberships(self):
        # In september, there is no expired members
        with mock.patch("bds.models.timezone.now", return_value=date(2022, 9, 1)):
            self.assertQuerysetEqual(BDSProfile.expired_members(), [])

        # In march, only bds-02's membership is expired
        with mock.patch("django.utils.timezone.now", return_value=date(2023, 3, 1)):
            self.assertQuerysetEqual(BDSProfile.expired_members(), [self.p_2])

        # During summer, all memberships are expired
        with mock.patch("django.utils.timezone.now", return_value=date(2023, 7, 1)):
            self.assertQuerysetEqual(
                BDSProfile.expired_members(),
                [self.p_1, self.p_2, self.p_3],
                ordered=False,
            )

    @mock.patch("gestioncof.signals.messages")
    def test_reset_memberships(self, _):
        url = reverse("bds:members.reset")

        # Reset during S1 does nothig
        with mock.patch("bds.models.timezone.now", return_value=date(2022, 9, 1)):
            self.client.force_login(
                self.admin, backend="django.contrib.auth.backends.ModelBackend"
            )
            resp = self.client.get(url)

            self.assertRedirects(resp, reverse("bds:members.expired"))

            self.assertQuerysetEqual(BDSProfile.expired_members(), [])

            self.assertQuerysetEqual(
                BDSProfile.objects.filter(is_member=True),
                [self.p_1, self.p_2, self.p_3],
                ordered=False,
            )

        # Reset in march
        with mock.patch("django.utils.timezone.now", return_value=date(2023, 3, 1)):
            self.client.force_login(
                self.admin, backend="django.contrib.auth.backends.ModelBackend"
            )
            resp = self.client.get(url)

            self.assertRedirects(resp, reverse("bds:members.expired"))

            # After a reset we have no expired memberships
            self.assertQuerysetEqual(BDSProfile.expired_members(), [])

            # Test reset attributes
            self.p_2.refresh_from_db()
            self.assertEqual(
                [self.p_2.is_member, self.p_2.mails_bds, self.p_2.cotisation_period],
                [False, False, "NO"],
            )

        # Reset during summer
        with mock.patch("django.utils.timezone.now", return_value=date(2023, 7, 1)):
            # bds-02's membership wa already reset
            self.assertQuerysetEqual(
                BDSProfile.expired_members(), [self.p_1, self.p_3], ordered=False
            )

            self.client.force_login(
                self.admin, backend="django.contrib.auth.backends.ModelBackend"
            )
            resp = self.client.get(url)

            self.assertRedirects(resp, reverse("bds:members.expired"))

            # After a reset we have no expired memberships
            self.assertQuerysetEqual(BDSProfile.expired_members(), [])

            # Test reset attributes
            self.p_1.refresh_from_db()
            self.assertEqual(
                [self.p_1.is_member, self.p_1.mails_bds, self.p_1.cotisation_period],
                [False, False, "NO"],
            )

            self.p_3.refresh_from_db()
            self.assertEqual(
                [self.p_3.is_member, self.p_3.mails_bds, self.p_3.cotisation_period],
                [False, False, "NO"],
            )
