from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie import fields
from tastypie.authentication import ApiKeyAuthentication, SessionAuthentication, MultiAuthentication
from tastypie.authorization import DjangoAuthorization
from tastypie.validation import Validation
from tastypie.exceptions import BadRequest
from tastypie.utils import trailing_slash
from tastypie.cache import NoCache

from django.core.urlresolvers import resolve
from django.conf.urls import url
from django.core.validators import validate_ipv4_address, validate_ipv6_address
from django.db.models import Q
from django.contrib.auth.models import User

from main.models import Zone, Record, View, record_type_choices, zone_type_choices, ServerGroup, Server, ServerConfig
from dns.dns_system_actions import GenerateZone, SaveConfig, CloneZone
import re

class RecordValidation(Validation):

    def is_valid(self, bundle, request=None):

        if not bundle.data:
            return {'__all__': 'No parameters passed'}

        errors = {}

        record_type = int(bundle.data['record_type'])
        host = bundle.data['host']
        answer = bundle.data['answer']
        zone = bundle.data['zone']

        if 'record_id' in bundle.data:
            record_id = int(bundle.data['record_id'])
        else:
            record_id = False

        view, args, kwargs = resolve(zone)
        zone_pk = kwargs['pk']

        record_type_text = dict(record_type_choices).get(record_type)

        if self.if_duplicate(host, answer, zone_pk, record_id):
            errors['duplicate'] = ['Duplicated host and answer']

        if self.if_same_host(host, record_type_text, zone_pk, record_id):
            errors['duplicate'] = ['Same host detected. RFC violation.']

        if record_type_text == 'A':
            try:
                validate_ipv4_address(answer)
            except:
                errors['answer'] = ['Should be IPv4 address']

            if not self.if_hostname(host):
                errors['host'] = ['Should be valid hostname']

        elif record_type_text == 'AAAA':
            try:
                validate_ipv6_address(answer)
            except:
                errors['answer'] = ['Should be IPv6 address']

            if not self.if_hostname(host) or host == '@':
                errors['host'] = ['Should be valid hostname']

        elif record_type_text == 'CNAME':

            if not self.if_fqdn(answer):
                errors['answer'] = ['Should be valid FQDN']

            if not self.if_hostname(host):
                errors['host'] = ['Should be valid hostname']
           
        elif record_type_text == 'NS':

            if not self.if_fqdn(answer):
                errors['answer'] = ['Should be valid FQDN']

            if not self.if_hostname(host):
                errors['host'] = ['Should be valid hostname']

        elif record_type_text == 'MX':
        
            if not self.if_fqdn(answer):
                errors['answer'] = ['Should be valid FQDN']

            if not self.if_hostname(host):
                errors['host'] = ['Should be valid hostname']

        elif record_type_text == 'PTR':
        
            if not self.if_fqdn(answer):
                errors['answer'] = ['Should be valid FQDN']
 
        return errors

    def if_fqdn(self, hostname):
        if len(hostname) > 255:
            return False

        if hostname[-1] == ".":
            hostname = hostname[:-1]
        else:
            return False