# -*- coding: utf-8 -*-
from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import MinValueValidator
from netfields import InetAddressField, NetManager
from netaddr import IPAddress
import ldapdb.models
from ldapdb.models.fields import CharField, IntegerField, ListField

from coin.models import CoinLdapSyncModel

# 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):
    # TODO: signal to IPSubnet when we are modified, so that is saves the
    # result into LDAP.  Actually, better: build a custom M2M relation
    # between NameServer and IPSubnet (see Capslock), and save in LDAP
    # there.
    dns_name = models.CharField(max_length=255,
                                help_text="Example: ns1.example.com")
    description = models.CharField(max_length=255, blank=True,
                                   verbose_name="human-readable name of the nameserver",
                                   help_text="Example: My first name server")
    # TODO: don't allow NULL owner (this is only here to allow migrations)
    owner = models.ForeignKey("members.Member", null=True)

    def __unicode__(self):
        return "{} ({})".format(self.description, self.dns_name) if self.description else 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")
    ttl = models.IntegerField(default=3600, verbose_name="TTL",
                              help_text="in seconds",
                              validators=[MinValueValidator(60)])
    ip_subnet = models.ForeignKey('resources.IPSubnet')

    objects = NetManager()

    def clean(self):
        if self.reverse:
            # Check that the reverse ends with a "." (add it if necessary)
            if not self.reverse.endswith('.'):
                self.reverse += '.'
        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 u"{} → {}".format(self.ip, self.reverse)
