# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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

# 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,
                                verbose_name="nom du serveur",
                                help_text="Exemple : ns1.example.com")
    description = models.CharField(max_length=255, blank=True,
                                   verbose_name="description du serveur",
                                   help_text="Exemple : Mon serveur de noms principal")
    owner = models.ForeignKey("members.Member", verbose_name="propriétaire")

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

    class Meta:
        verbose_name = 'serveur de noms'
        verbose_name_plural = 'serveurs de noms'


class ReverseDNSEntry(models.Model):
    ip = InetAddressField(unique=True, verbose_name='adresse IP')
    reverse = models.CharField(max_length=255, verbose_name='reverse',
                               help_text="Nom à associer à l'adresse IP")
    ttl = models.IntegerField(default=3600, verbose_name="TTL",
                              help_text="en secondes",
                              validators=[MinValueValidator(60)])
    ip_subnet = models.ForeignKey('resources.IPSubnet',
                                  verbose_name='sous-réseau IP')

    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 "{} → {}".format(self.ip, self.reverse)

    class Meta:
        verbose_name = 'entrée DNS inverse'
        verbose_name_plural = 'entrées DNS inverses'
