"""
Tests for :py:mod:`domains.models`.

"""
from unittest.mock import patch

from django.test import TestCase
from django.contrib.auth import get_user_model

from domains.models import HostingDomain, MailDomain

from hostingpackages.models import CustomerHostingPackage, HostingPackageTemplate

User = get_user_model()

TEST_USER = "test"


class MailDomainTest(TestCase):
    def test___str__(self):
        md = MailDomain.objects.create(domain="example.org")
        self.assertEqual(str(md), "example.org")

    def test_get_mailaddresses(self):
        md = MailDomain.objects.create(domain="example.org")
        from managemails.models import MailAddress

        addrmock = MailAddress.objects.create(localpart="info", domain=md)
        self.assertIn(addrmock, md.get_mailaddresses())
        self.assertIn(addrmock, md.mailaddresses)


class HostingDomainManagerTest(TestCase):
    def _setup_hosting_package(self):
        template = HostingPackageTemplate.objects.create(
            name="testpackagetemplate", mailboxcount=0, diskspace=1, diskspace_unit=0
        )
        customer = User.objects.create_user(username=TEST_USER)
        package = CustomerHostingPackage.objects.create_from_template(
            customer, template, "testpackage"
        )
        with patch("hostingpackages.models.settings") as hmsettings:
            hmsettings.OSUSER_DEFAULT_GROUPS = []
            package.save()
        return package

    def test_create_for_hosting_package_with_commit(self):
        package = self._setup_hosting_package()
        hostingdomain = HostingDomain.objects.create_for_hosting_package(
            package, "example.org", True
        )

        self.assertIsNotNone(hostingdomain)
        self.assertTrue(hostingdomain.customer, package.customer)

    def test_create_for_hosting_package_no_commit(self):
        package = self._setup_hosting_package()
        hostingdomain = HostingDomain.objects.create_for_hosting_package(
            package, "example.org", False
        )

        self.assertIsNotNone(hostingdomain)
        self.assertTrue(hostingdomain.customer, package.customer)


class HostingDomainTest(TestCase):
    def test___str__(self):
        hostingdomain = HostingDomain(domain="test")
        self.assertEqual(str(hostingdomain), "test")
