"""
This module provides tests for :py:mod:`osusers.views`.

"""

from unittest.mock import MagicMock, patch

from django.contrib.auth import get_user_model
from django.test import TestCase, TransactionTestCase
from django.urls import reverse

from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate
from osusers.models import SshPublicKey
from osusers.views import AddSshPublicKey, DeleteSshPublicKey, EditSshPublicKeyComment

User = get_user_model()

TEST_USER = "test"
TEST_PASSWORD = "secret"
TEST_EMAIL = "test@example.org"
EXAMPLE_KEY = "".join(
    (
        "ssh-rsa ",
        "AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb",
        "YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ",
        "5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE=",
    )
)


class HostingPackageAwareTestMixin(object):
    # noinspection PyMethodMayBeStatic
    def _setup_hosting_package(self, customer):
        template = HostingPackageTemplate.objects.create(
            name="testpackagetemplate", mailboxcount=10, diskspace=1, diskspace_unit=0
        )
        package = CustomerHostingPackage.objects.create_from_template(
            customer, template, "testpackage"
        )
        with patch("hostingpackages.models.settings") as hmsettings:
            hmsettings.OSUSER_DEFAULT_GROUPS = []
            package.save()
        return package


class AddSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
    def setUp(self):
        self.customer = User.objects.create_user(
            username=TEST_USER, password=TEST_PASSWORD
        )
        self.package = self._setup_hosting_package(self.customer)

    def _get_url(self):
        return reverse("add_ssh_key", kwargs={"package": self.package.id})

    def test_get_anonymous(self):
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_regular_user(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_other_regular_user(self):
        User.objects.create_user("test2", password=TEST_PASSWORD)
        self.client.login(username="test2", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_staff_user(self):
        User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
        self.client.login(username="admin", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_template(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertTemplateUsed(response, "osusers/sshpublickey_create.html")

    def test_get_form_kwargs(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        view = AddSshPublicKey(
            request=MagicMock(), kwargs={"package": str(self.package.pk)}
        )
        the_kwargs = view.get_form_kwargs()
        self.assertIn("hostingpackage", the_kwargs)
        self.assertEqual(the_kwargs["hostingpackage"], self.package)

    def test_get_context_data(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertIn("customer", response.context)
        self.assertEqual(response.context["customer"], self.customer)
        self.assertIn("osuser", response.context)
        self.assertEqual(response.context["osuser"], self.package.osuser.username)

    def test_form_valid_redirect(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(
            self._get_url(), data={"publickeytext": EXAMPLE_KEY}
        )
        self.assertRedirects(response, self.package.get_absolute_url())

    def test_form_valid_message(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(
            self._get_url(), follow=True, data={"publickeytext": EXAMPLE_KEY}
        )
        messages = list(response.context["messages"])
        self.assertEqual(len(messages), 1)
        self.assertEqual(
            "Successfully added new ssh-rsa SSH public key.".format(
                username=self.package.osuser.username
            ),
            str(messages[0]),
        )


class DeleteSshPublicKeyTest(HostingPackageAwareTestMixin, TestCase):
    def setUp(self):
        self.customer = User.objects.create_user(
            username=TEST_USER, password=TEST_PASSWORD
        )
        self.package = self._setup_hosting_package(self.customer)
        self.sshkey = SshPublicKey.objects.create(
            user=self.package.osuser, algorithm="good", data="key", comment="comment"
        )

    def _get_url(self):
        return reverse(
            "delete_ssh_key", kwargs={"package": self.package.id, "pk": self.sshkey.id}
        )

    def test_get_anonymous(self):
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_regular_user(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_other_regular_user(self):
        User.objects.create_user("test2", password=TEST_PASSWORD)
        self.client.login(username="test2", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_staff_user(self):
        User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
        self.client.login(username="admin", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_template(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertTemplateUsed(response, "osusers/sshpublickey_confirm_delete.html")

    def test_get_queryset(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        view = DeleteSshPublicKey(
            request=MagicMock(),
            kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
        )
        queryset = view.get_queryset()
        self.assertQuerysetEqual(queryset, [repr(self.sshkey)], transform=repr)

    def test_get_context_data(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        for key in ("hostingpackage", "customer", "osuser"):
            self.assertIn(key, response.context)
        self.assertEqual(response.context["hostingpackage"], self.package)
        self.assertEqual(response.context["customer"], self.customer)
        self.assertEqual(response.context["osuser"], self.package.osuser.username)

    def test_get_success_url(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(self._get_url(), data={"comment": "new comment"})
        self.assertRedirects(
            response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
        )


class EditSshPublicKeyCommentTest(HostingPackageAwareTestMixin, TransactionTestCase):
    def setUp(self):
        self.customer = User.objects.create_user(
            username=TEST_USER, password=TEST_PASSWORD
        )
        self.package = self._setup_hosting_package(self.customer)
        self.sshkey = SshPublicKey.objects.create(
            user=self.package.osuser, algorithm="good", data="key", comment="comment"
        )

    def _get_url(self):
        return reverse(
            "edit_ssh_key_comment",
            kwargs={"package": self.package.id, "pk": self.sshkey.id},
        )

    def test_get_anonymous(self):
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_regular_user(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_other_regular_user(self):
        User.objects.create_user("test2", password=TEST_PASSWORD)
        self.client.login(username="test2", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_staff_user(self):
        User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
        self.client.login(username="admin", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_template(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertTemplateUsed(response, "osusers/sshpublickey_edit_comment.html")

    def test_get_queryset(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        view = EditSshPublicKeyComment(
            request=MagicMock(),
            kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
        )
        queryset = view.get_queryset()
        self.assertQuerysetEqual(queryset, [repr(self.sshkey)], transform=repr)

    def test_get_form_kwargs(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        view = EditSshPublicKeyComment(
            request=MagicMock(),
            kwargs={"package": str(self.package.pk), "pk": str(self.sshkey.pk)},
        )
        the_kwargs = view.get_form_kwargs()
        self.assertIn("hostingpackage", the_kwargs)
        self.assertEqual(the_kwargs["hostingpackage"], self.package)

    def test_get_context_data(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        for key in ("hostingpackage", "customer", "osuser"):
            self.assertIn(key, response.context)
        self.assertEqual(response.context["hostingpackage"], self.package)
        self.assertEqual(response.context["customer"], self.customer)
        self.assertEqual(response.context["osuser"], self.package.osuser.username)

    def test_get_success_url(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(self._get_url(), data={"comment": "new comment"})
        self.assertRedirects(
            response, reverse("list_ssh_keys", kwargs={"package": self.package.id})
        )


class ListSshPublicKeysTest(HostingPackageAwareTestMixin, TestCase):
    def setUp(self):
        self.customer = User.objects.create_user(
            username=TEST_USER, password=TEST_PASSWORD
        )
        self.package = self._setup_hosting_package(self.customer)

    def _get_url(self):
        return reverse("list_ssh_keys", kwargs={"package": self.package.id})

    def test_get_anonymous(self):
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_regular_user(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_other_regular_user(self):
        User.objects.create_user("test2", password=TEST_PASSWORD)
        self.client.login(username="test2", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_staff_user(self):
        User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
        self.client.login(username="admin", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_template(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertTemplateUsed(response, "osusers/sshpublickey_list.html")

    def test_get_context_data(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        for key in ("hostingpackage", "customer", "osuser"):
            self.assertIn(key, response.context)
        self.assertEqual(response.context["hostingpackage"], self.package)
        self.assertEqual(response.context["customer"], self.customer)
        self.assertEqual(response.context["osuser"], self.package.osuser.username)


class SetOsUserPasswordTest(HostingPackageAwareTestMixin, TestCase):
    def setUp(self):
        self.customer = User.objects.create_user(
            username=TEST_USER, password=TEST_PASSWORD
        )
        self.package = self._setup_hosting_package(self.customer)

    def _get_url(self):
        return reverse(
            "set_osuser_password", kwargs={"slug": self.package.osuser.username}
        )

    def test_get_anonymous(self):
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_regular_user(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_other_regular_user(self):
        User.objects.create_user("test2", password=TEST_PASSWORD)
        self.client.login(username="test2", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 403)

    def test_get_staff_user(self):
        User.objects.create_superuser("admin", email=TEST_EMAIL, password=TEST_PASSWORD)
        self.client.login(username="admin", password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertEqual(response.status_code, 200)

    def test_get_template(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertTemplateUsed(response, "osusers/user_setpassword.html")

    def test_get_context_data(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.get(self._get_url())
        self.assertIn("customer", response.context)
        self.assertEqual(response.context["customer"], self.customer)

    def test_form_valid_redirect(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(
            self._get_url(),
            data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
        )
        self.assertRedirects(response, self.package.get_absolute_url())

    def test_form_valid_message(self):
        self.client.login(username=TEST_USER, password=TEST_PASSWORD)
        response = self.client.post(
            self._get_url(),
            follow=True,
            data={"password1": TEST_PASSWORD, "password2": TEST_PASSWORD},
        )
        messages = list(response.context["messages"])
        self.assertEqual(len(messages), 1)
        self.assertEqual(
            "New password for {username} has been set successfully.".format(
                username=self.package.osuser.username
            ),
            str(messages[0]),
        )
