"""
This module provides tests for :py:mod:`managemails.forms`.

"""
from unittest.mock import MagicMock, Mock, patch

from django.forms import ValidationError
from django.test import TestCase
from django.urls import reverse

from osusers.tests.testutils import create_test_user

from domains.models import MailDomain
from managemails.forms import (
    MAILBOX_OR_FORWARDS,
    AddMailAddressForm,
    ChangeMailboxPasswordForm,
    CreateMailboxForm,
    EditMailAddressForm,
    MailAddressFieldMixin,
    multiple_email_validator,
)
from managemails.models import MailAddress, Mailbox
from taskresults.tests.testutils import TestCaseWithCeleryTasks


class CreateMailboxFormTest(TestCase):
    def test_constructor_needs_hosting_package(self):
        instance = Mailbox()
        with self.assertRaises(KeyError):
            CreateMailboxForm(instance)

    def test_constructor(self):
        hosting_package = Mock(id=42)
        instance = MagicMock()
        form = CreateMailboxForm(instance, hostingpackage=hosting_package)
        self.assertTrue(hasattr(form, "hosting_package"))
        self.assertEqual(form.hosting_package, hosting_package)
        self.assertTrue(hasattr(form, "helper"))
        self.assertEqual(
            form.helper.form_action, reverse("create_mailbox", kwargs={"package": 42})
        )
        self.assertIn("password1", form.fields)
        self.assertIn("password2", form.fields)
        self.assertEqual(form.helper.inputs[0].name, "submit")

    @patch("managemails.forms.Mailbox.objects")
    def test_save(self, mailbox_objects):
        osuser = MagicMock()
        hostingpackage = Mock(id=42, osuser=osuser)
        instance = MagicMock()
        form = CreateMailboxForm(
            instance=instance,
            hostingpackage=hostingpackage,
            data={"password1": "secret", "password2": "secret"},
        )
        mailbox_objects.get_next_mailbox_name.return_value = "mailbox23"
        self.assertTrue(form.is_valid())
        form.save(commit=False)
        self.assertEqual(osuser, form.instance.osuser)
        self.assertEqual("mailbox23", form.instance.username)
        instance.set_password.assert_called_with("secret")


class ChangeMailboxPasswordFormTest(TestCase):
    def test_constructor_needs_hostingpackage(self):
        instance = MagicMock()
        with self.assertRaises(KeyError):
            ChangeMailboxPasswordForm(instance)

    def test_constructor(self):
        hostingpackage = Mock(id=42)
        instance = MagicMock(username="testuser")
        form = ChangeMailboxPasswordForm(
            instance=instance, hostingpackage=hostingpackage
        )
        self.assertTrue(hasattr(form, "hosting_package"))
        self.assertEqual(form.hosting_package, hostingpackage)
        self.assertTrue(hasattr(form, "helper"))
        self.assertEqual(
            form.helper.form_action,
            reverse(
                "change_mailbox_password", kwargs={"package": 42, "slug": "testuser"}
            ),
        )
        self.assertIn("password1", form.fields)
        self.assertIn("password2", form.fields)
        self.assertEqual(form.helper.inputs[0].name, "submit")

    def test_save(self):
        hostingpackage = Mock(id=42)
        instance = MagicMock(username="testuser")
        form = ChangeMailboxPasswordForm(
            instance=instance,
            hostingpackage=hostingpackage,
            data={"password1": "newsecret", "password2": "newsecret"},
        )
        self.assertTrue(form.is_valid())
        form.save(commit=False)
        instance.set_password.assert_called_with("newsecret")


class MultipleEmailValidatorTest(TestCase):
    def test_valid_single_address(self):
        self.assertEqual(
            "test@example.org", multiple_email_validator("test@example.org")
        )

    def test_valid_multiple_addresses(self):
        self.assertEqual(
            "test1@example.org,test2@example.org",
            multiple_email_validator("test1@example.org,test2@example.org"),
        )

    def test_empty(self):
        self.assertEqual("", multiple_email_validator(""))

    def test_none(self):
        self.assertIsNone(multiple_email_validator(None))

    def test_invalid_single_address(self):
        with self.assertRaises(ValidationError):
            multiple_email_validator("no@ddress")

    def test_invalid_multiple_addresses(self):
        with self.assertRaises(ValidationError):
            multiple_email_validator("test1@example.org,no@ddress")


class MailAddressFieldMixinTest(TestCase):
    def test_fields_defined(self):
        form = MailAddressFieldMixin()
        self.assertIn("mailbox_or_forwards", form.fields)
        self.assertIn("mailbox", form.fields)
        self.assertIn("forwards", form.fields)


def create_test_mailbox(os_user=None):
    if os_user is None:
        os_user = create_test_user()

    mail_box = Mailbox.objects.create(osuser=os_user, username="mailbox23")
    mail_box.set_password("test")

    return mail_box


def create_test_mail_domain():
    return MailDomain.objects.create(domain="example.org")


class AddMailAddressFormTest(TestCaseWithCeleryTasks):
    def setUp(self) -> None:
        super().setUp()
        self.mail_domain = create_test_mail_domain()
        self.instance = MailAddress()
        self.os_user = create_test_user()
        self.hosting_package = create_test_hosting_package(os_user=self.os_user)

    def test_constructor_needs_hosting_package(self):
        with self.assertRaises(KeyError):
            AddMailAddressForm(instance=self.instance, maildomain=MagicMock())

    def test_constructor_needs_mail_domain(self):
        with self.assertRaises(KeyError):
            AddMailAddressForm(instance=self.instance, hostingpackage=MagicMock())

    def test_constructor(self):
        form = AddMailAddressForm(
            instance=self.instance, hostingpackage=self.hosting_package, maildomain=self.mail_domain
        )
        self.assertIn("mailbox_or_forwards", form.fields)
        self.assertIn("mailbox", form.fields)
        self.assertIn("forwards", form.fields)
        self.assertTrue(hasattr(form, "hosting_package"))
        self.assertEqual(form.hosting_package, self.hosting_package)
        self.assertTrue(hasattr(form, "maildomain"))
        self.assertEqual(form.maildomain, self.mail_domain)
        self.assertTrue(hasattr(form, "helper"))
        self.assertEqual(
            form.helper.form_action,
            reverse("add_mailaddress", kwargs={"package": 42, "domain": "example.org"}),
        )
        self.assertEqual(len(form.helper.layout), 2)
        self.assertEqual(form.helper.layout[1].name, "submit")

    def test_clean_localpart_valid(self):
        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org",
            },
        )
        self.assertTrue(form.is_valid())
        self.assertEqual("test", form.clean_localpart())

    def test_clean_localpart_duplicate(self):
        MailAddress.objects.create(localpart="test", domain=self.mail_domain)

        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org",
            },
        )
        self.assertFalse(form.is_valid())
        self.assertIn("localpart", form.errors)

    def test_clean_no_mailbox_choice(self):
        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
            },
        )
        self.assertFalse(form.is_valid())
        self.assertIn("mailbox", form.errors)

    def test_clean_no_forward_address_choice(self):
        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
            },
        )
        self.assertFalse(form.is_valid())
        self.assertIn("forwards", form.errors)

    def test_save_with_forwards_no_commit(self):
        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org,test3@example.org",
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=False)
        self.assertEqual(self.mail_domain, self.instance.domain)

    def test_save_with_forwards_commit(self):
        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org,test3@example.org",
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=True)
        self.assertEqual(self.mail_domain, self.instance.domain)
        forwards = list(
            self.instance.mailaddressforward_set.values_list("target", flat=True).order_by(
                "target"
            )
        )
        self.assertEqual(len(forwards), 2)
        self.assertEqual(forwards, ["test2@example.org", "test3@example.org"])

    def test_save_with_mailbox_no_commit(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=False)
        self.assertEqual(self.mail_domain, self.instance.domain)

    def test_save_with_mailbox_commit(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=True)
        self.assertEqual(self.mail_domain, self.instance.domain)

    def test_save_with_other_choice(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = AddMailAddressForm(
            instance=self.instance,
            hostingpackage=self.hosting_package,
            maildomain=self.mail_domain,
            data={
                "localpart": "test",
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())
        form.cleaned_data["mailbox_or_forwards"] = -1
        form.save(commit=True)


def create_test_hosting_package(os_user=None):
    if os_user is None:
        os_user = create_test_user()

    return MagicMock(id=42, osuser=os_user)


class EditMailAddressFormTest(TestCaseWithCeleryTasks):
    def setUp(self) -> None:
        super().setUp()
        self.os_user = create_test_user()
        self.hosting_package = create_test_hosting_package(os_user=self.os_user)
        self.mail_domain = create_test_mail_domain()
        self.instance = MailAddress.objects.create(localpart="test", domain=self.mail_domain)

    def test_constructor_needs_hosting_package(self):
        instance = MagicMock()
        with self.assertRaises(KeyError):
            EditMailAddressForm(instance=instance, maildomain=MagicMock())

    def test_constructor_needs_mail_domain(self):
        instance = MagicMock()
        with self.assertRaises(KeyError):
            EditMailAddressForm(instance=instance, hostingpackage=MagicMock())

    def test_constructor(self):
        form = EditMailAddressForm(
            instance=self.instance, maildomain=self.mail_domain, hostingpackage=self.hosting_package
        )
        self.assertIn("mailbox_or_forwards", form.fields)
        self.assertIn("mailbox", form.fields)
        self.assertIn("forwards", form.fields)
        self.assertTrue(hasattr(form, "hosting_package"))
        self.assertEqual(form.hosting_package, self.hosting_package)
        self.assertTrue(hasattr(form, "maildomain"))
        self.assertEqual(form.maildomain, self.mail_domain)
        self.assertTrue(hasattr(form, "helper"))
        self.assertEqual(
            form.helper.form_action,
            reverse(
                "edit_mailaddress",
                kwargs={"package": 42, "domain": "example.org", "pk": self.instance.pk},
            ),
        )
        self.assertEqual(len(form.helper.layout), 2)
        self.assertEqual(form.helper.layout[1].name, "submit")

    def test_clean_no_mailbox_choice(self):
        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox},
        )
        self.assertFalse(form.is_valid())
        self.assertIn("mailbox", form.errors)

    def test_clean_no_forward_address_choice(self):
        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={"mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards},
        )
        self.assertFalse(form.is_valid())
        self.assertIn("forwards", form.errors)

    def test_save_with_forwards_no_commit(self):
        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org,test3@example.org",
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=False)

    def test_save_with_forwards_commit(self):
        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.forwards,
                "forwards": "test2@example.org,test3@example.org",
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=True)

    def test_save_with_mailbox_no_commit(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=False)

        self.instance.refresh_from_db()
        self.assertFalse(hasattr(self.instance, "mailaddressmailbox"))

    def test_save_with_mailbox_commit(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())
        form.save(commit=True)

        self.instance.refresh_from_db()
        self.assertEqual(self.instance.mailaddressmailbox.mailbox, mail_box)

    def test_save_with_other_choice(self):
        mail_box = create_test_mailbox(os_user=self.os_user)

        form = EditMailAddressForm(
            instance=self.instance,
            maildomain=self.mail_domain,
            hostingpackage=self.hosting_package,
            data={
                "mailbox_or_forwards": MAILBOX_OR_FORWARDS.mailbox,
                "mailbox": mail_box,
            },
        )
        self.assertTrue(form.is_valid())

        form.cleaned_data["mailbox_or_forwards"] = -1
        form.save(commit=True)
