"""
Test for models.

"""
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, override_settings

from hostingpackages.models import (
    DISK_SPACE_UNITS,
    CustomerHostingPackage,
    HostingPackageTemplate,
)

User = get_user_model()


class CustomerHostingPackageTest(TestCase):
    def setUp(self) -> None:
        self.user = User.objects.create(username="test")
        self.template = HostingPackageTemplate.objects.create(
            mailboxcount=10,
            diskspace=100,
            diskspace_unit=DISK_SPACE_UNITS.M,
            description="Test package 1 - Description",
            name="Test package 1",
        )

    @override_settings(OSUSER_DEFAULT_GROUPS=[])
    def test_get_disk_space_bytes(self):
        self.template.diskspace = 10
        self.template.diskspace_unit = DISK_SPACE_UNITS.G
        self.template.save()
        package = CustomerHostingPackage.objects.create_from_template(
            customer=self.user, template=self.template, name="customer",
        )
        package.save()
        self.assertEqual(package.get_disk_space(), 10 * 1024 ** 3)

    @override_settings(OSUSER_DEFAULT_GROUPS=[])
    def test_get_disk_space_mib(self):
        self.template.diskspace = 10
        self.template.diskspace_unit = DISK_SPACE_UNITS.G
        self.template.save()
        package = CustomerHostingPackage.objects.create_from_template(
            customer=self.user, template=self.template, name="customer",
        )
        package.save()
        self.assertEqual(package.get_disk_space(DISK_SPACE_UNITS.M), 10 * 1024)

    @override_settings(OSUSER_DEFAULT_GROUPS=[])
    def test_get_quota(self):
        self.template.diskspace = 256
        self.template.diskspace_unit = DISK_SPACE_UNITS.M
        self.template.save()
        package = CustomerHostingPackage.objects.create_from_template(
            customer=self.user, template=self.template, name="customer",
        )
        package.save()
        self.assertEqual(package.get_quota(), (262144, 275251))

    @override_settings(OSUSER_DEFAULT_GROUPS=["testgroup"])
    def test_additional_group_not_defined(self):
        with self.assertRaises(ImproperlyConfigured) as ctx:
            package = CustomerHostingPackage.objects.create_from_template(
                customer=self.user, template=self.template, name="Test customer package",
            )
            package.save()
        self.assertIn("testgroup", str(ctx.exception))
