from django.db import models
from django.core.exceptions import ValidationError
from netfields import InetAddressField, NetManager
from netaddr import IPAddress

# TODO: validate DNS names with this regex
REGEX = r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})\.?$'

class NameServer(models.Model):
    dns_name = models.CharField(max_length=255,
                                help_text="Example: ns1.example.com")
    description = models.CharField(max_length=255,
                                   verbose_name="human-readable name of the nameserver",
                                   help_text="Example: My first name server")

    def __unicode__(self):
        return "{} ({})".format(self.description, self.dns_name)


class ReverseDNSEntry(models.Model):
    ip = InetAddressField(unique=True)
    reverse = models.CharField(max_length=255,
                               verbose_name="hostname to associate to the IP")
    ip_subnet = models.ForeignKey('resources.IPSubnet')

    objects = NetManager()

    def clean(self):
        if self.ip:
            if not self.ip in self.ip_subnet.inet:
                raise ValidationError('IP address must be included in the IP subnet.')

    def __unicode__(self):
        return str(self.ip)
