"""
This module defines form classes for domain editing.

"""
from __future__ import absolute_import

import re

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
from django import forms
from django.urls import reverse
from django.utils.translation import gettext as _

from .models import HostingDomain


def relative_domain_validator(value):
    """
    This validator ensures that the given value is a valid lowercase domain
    name.

    """
    if len(value) > 254:
        raise forms.ValidationError(_("host name too long"), code="too-long")
    allowed = re.compile(r"(?!-)[a-z\d-]{1,63}(?<!-)$")
    if not all(allowed.match(x) for x in value.split(".")):
        raise forms.ValidationError(_("invalid domain name"))


class CreateHostingDomainForm(forms.ModelForm):
    """
    This form is used to create new HostingDomain instances.

    """

    class Meta:
        model = HostingDomain
        fields = ["domain"]

    def __init__(self, instance, *args, **kwargs):
        self.hosting_package = kwargs.pop("hostingpackage")
        super(CreateHostingDomainForm, self).__init__(*args, **kwargs)
        self.fields["domain"].validators.append(relative_domain_validator)
        self.helper = FormHelper()
        self.helper.form_action = reverse(
            "create_hosting_domain", kwargs={"package": self.hosting_package.id}
        )
        self.helper.layout = Layout(
            "domain",
            Submit("submit", _("Add Hosting Domain")),
        )

    def clean(self):
        self.cleaned_data = super(CreateHostingDomainForm, self).clean()
        self.cleaned_data["hosting_package"] = self.hosting_package

    def save(self, commit=True):
        return HostingDomain.objects.create_for_hosting_package(
            commit=commit, **self.cleaned_data
        )

    def save_m2m(self):
        pass
