"""
This module contains tests for :py:mod:`managemails.models`
"""
from django.contrib.auth import get_user_model
from django.test import TestCase, TransactionTestCase
from django.test.utils import override_settings
from passlib.handlers.sha2_crypt import sha512_crypt

from domains.models import MailDomain
from managemails.models import MailAddress, Mailbox
from osusers.models import User
from taskresults.tests.testutils import TestCaseWithCeleryTasks

Customer = get_user_model()


class MailboxTest(TestCaseWithCeleryTasks):
    def setUp(self):
        super(MailboxTest, self).setUp()
        self.customer = Customer.objects.create_user("test")

    def test_set_password(self):
        user = User.objects.create_user(self.customer)
        mb = Mailbox.objects.create(username="test", osuser=user)
        mb.set_password("test")
        self.assertTrue(sha512_crypt.verify("test", mb.password))

    def test___str__(self):
        user = User.objects.create_user(self.customer)
        mb = Mailbox.objects.create(username="test", osuser=user)
        mb.set_password("test")
        self.assertEqual(str(mb), "test")

    def test_save(self):
        user = User.objects.create_user(self.customer)

        self.resetCeleryTasks()

        mb = Mailbox.objects.create_mailbox(user)
        self.assertIsNotNone(mb.pk)

        self.assertCeleryTasksRun([
            (1, "handle_mailbox_created"),
        ])

    def test_delete(self):
        user = User.objects.create_user(self.customer)
        mb = Mailbox.objects.create_mailbox(user)

        self.resetCeleryTasks()

        mb.delete()
        self.assertIsNone(mb.pk)

        self.assertCeleryTasksRun([
            (1, "handle_mailbox_deleted"),
        ])

    def test_get_mail_addresses(self):
        user = User.objects.create_user(self.customer)
        mb = Mailbox.objects.create_mailbox(user)
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        address.set_mailbox(mb)
        mailaddresses = mb.get_mailaddresses()
        self.assertEqual(len(mailaddresses), 1)
        self.assertIn(address, mailaddresses)


class MailAddressTest(TestCaseWithCeleryTasks):
    def test__str__(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        self.assertEqual(str(ma), "test@example.org")

    def test_set_mailbox_fresh(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb)
        self.assertIn(ma, mb.get_mailaddresses())

    def test_set_mailbox_reassing(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb)
        mb2 = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb2)
        self.assertIn(ma, mb2.get_mailaddresses())
        self.assertNotIn(ma, mb.get_mailaddresses())

    def test_set_mailbox_with_forwards(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_forward_addresses(["test2@example.org"])
        ma.set_mailbox(mb)
        self.assertEqual(ma.mailaddressforward_set.count(), 0)
        self.assertIn(ma, mb.get_mailaddresses())

    def test_set_mailbox_with_unsaved_address(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb)
        self.assertIn(ma, mb.get_mailaddresses())

    def test_set_mailbox_fresh_no_commit(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb, commit=False)
        self.assertNotIn(ma, mb.get_mailaddresses())

    def test_set_mailbox_with_unsaved_address_no_commit(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb, commit=False)
        self.assertNotIn(ma, mb.get_mailaddresses())

    def test_set_forward_addresses_fresh(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        ma.set_forward_addresses(["test2@example.org"])

        def get_target(maf):
            return maf.target

        self.assertQuerysetEqual(
            ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
        )

    def test_set_forward_addresses_unsaved(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress(localpart="test", domain=md)
        ma.set_forward_addresses(["test2@example.org"])

        def get_target(maf):
            return maf.target

        self.assertQuerysetEqual(
            ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
        )

    def test_set_forward_addresses_replace_forwards(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        ma.set_forward_addresses(["test2@example.org"])
        ma.set_forward_addresses(["test3@example.org"])

        def get_target(maf):
            return maf.target

        self.assertQuerysetEqual(
            ma.mailaddressforward_set.all(), ["test3@example.org"], get_target
        )

    def test_set_forward_addresses_add_forwards(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        ma.set_forward_addresses(["test2@example.org"])
        ma.set_forward_addresses(["test2@example.org", "test3@example.org"])

        def get_target(maf):
            return maf.target

        self.assertQuerysetEqual(
            ma.mailaddressforward_set.all(),
            ["test2@example.org", "test3@example.org"],
            get_target,
            ordered=False,
        )

    def test_set_forward_addresses_replace_mailbox(self):
        customer = Customer.objects.create_user("test")
        user = User.objects.create_user(customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb)
        ma.set_forward_addresses(["test2@example.org"])
        self.assertNotIn(ma, mb.get_mailaddresses())

        def get_target(maf):
            return maf.target

        self.assertQuerysetEqual(
            ma.mailaddressforward_set.all(), ["test2@example.org"], get_target
        )

    def test_set_forward_addresses_fresh_no_commit(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress.objects.create(localpart="test", domain=md)
        mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
        self.assertEqual(ma.mailaddressforward_set.count(), 0)
        self.assertEqual(mafwds[0].target, "test2@example.org")

    def test_set_forward_address_unsaved_no_commit(self):
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress(localpart="test", domain=md)
        mafwds = ma.set_forward_addresses(["test2@example.org"], commit=False)
        self.assertEqual(ma.mailaddressforward_set.count(), 0)
        self.assertEqual(mafwds[0].target, "test2@example.org")


class MailboxManagerTest(TestCaseWithCeleryTasks):
    def setUp(self):
        super(MailboxManagerTest, self).setUp()
        self.customer = Customer.objects.create_user("test")
        self.user = User.objects.create_user(self.customer)

    def test_get_next_mailbox_name_fresh(self):
        mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
        self.assertEqual(mailboxname, "{}p01".format(self.user.username))

    def test_get_next_mailbox_name_second(self):
        Mailbox.objects.create_mailbox(self.user)
        mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
        self.assertEqual(mailboxname, "{}p02".format(self.user.username))

    def test_get_next_mailbox_name_gap_detection(self):
        mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(3)]
        mailboxes[1].delete()
        mailboxname = Mailbox.objects.get_next_mailbox_name(self.user)
        self.assertEqual(mailboxname, "{}p02".format(self.user.username))

    def test_unused_or_own_fresh(self):
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        mailboxes = Mailbox.objects.unused_or_own(address, self.user)
        self.assertQuerysetEqual(mailboxes, [])

    def test_unused_or_own_unassigned(self):
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
        assignable = Mailbox.objects.unused_or_own(address, self.user)
        self.assertQuerysetEqual(
            assignable, [repr(mb) for mb in mailboxes], transform=repr
        )

    def test_unused_or_own_assigned(self):
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
        address.set_mailbox(mailboxes[0])
        assignable = Mailbox.objects.unused_or_own(address, self.user)
        self.assertQuerysetEqual(
            assignable, [repr(mb) for mb in mailboxes], transform=repr
        )

    def test_unused_or_own_assigned_other(self):
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        address2 = MailAddress.objects.create(localpart="test2", domain=md)
        mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
        address2.set_mailbox(mailboxes[0])
        assignable = Mailbox.objects.unused_or_own(address, self.user)
        self.assertQuerysetEqual(assignable, [repr(mailboxes[1])], transform=repr)

    def test_unused_fresh(self):
        mailboxes = Mailbox.objects.unused(self.user)
        self.assertQuerysetEqual(mailboxes, [])

    def test_unused_unassigned(self):
        mailbox = Mailbox.objects.create_mailbox(self.user)
        mailboxes = Mailbox.objects.unused(self.user)
        self.assertQuerysetEqual(mailboxes, [repr(mailbox)], transform=repr)

    def test_unused_assigned(self):
        md = MailDomain.objects.create(domain="example.org")
        address = MailAddress.objects.create(localpart="test", domain=md)
        mailboxes = [Mailbox.objects.create_mailbox(self.user) for _ in range(2)]
        address.set_mailbox(mailboxes[0])
        assignable = Mailbox.objects.unused(self.user)
        self.assertQuerysetEqual(assignable, [repr(mailboxes[1])], transform=repr)

    def test_create_mailbox_no_password(self):
        mailbox = Mailbox.objects.create_mailbox(self.user)
        self.assertEqual(mailbox.osuser, self.user)
        self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
        self.assertEqual(mailbox.password, "")

    def test_create_mailbox_with_password(self):
        mailbox = Mailbox.objects.create_mailbox(self.user, "test")
        self.assertEqual(mailbox.osuser, self.user)
        self.assertEqual(mailbox.username, "{}p01".format(self.user.username))
        self.assertTrue(sha512_crypt.verify("test", mailbox.password))


class MailAddressMailboxTest(TestCaseWithCeleryTasks):
    def setUp(self):
        super(MailAddressMailboxTest, self).setUp()
        self.customer = Customer.objects.create_user("test")

    def test___str__(self):
        user = User.objects.create_user(self.customer)
        md = MailDomain.objects.create(domain="example.org")
        ma = MailAddress(localpart="test", domain=md)
        mb = Mailbox.objects.create_mailbox(user)
        ma.set_mailbox(mb)
        self.assertEqual(str(ma.mailaddressmailbox), mb.username)
