#!/usr/bin/venv python
# -*- coding: utf-8 -*-

import whois
import dns.resolver
import dns.name
from config import DNS_QUERIES_TYPE


class DNSChecker:
    def __init__(self, api_key, fqdn, rrtype=DNS_QUERIES_TYPE):
        self._fqdn = fqdn
        self._rrtype = rrtype

    def checkDomainExist(self):
        """
        This function check if the domain exist
        """
        try:
            res_query = dns.resolver.resolve(self._fqdn, 'NS')
        except dns.resolver.NoAnswer:
            return False
        except dns.resolver.NXDOMAIN:
            return False
        return True

    def whois(self):
        """
        This function will get an whois request for having some information
        regarding the domain
        """
        report = dict()
        w = whois.whois(self._fqdn)
        report['domain_name'] = w.domain_name
        report['expiration_date'] = w.expiration_date
        report['creation_date'] = w.creation_date
        report['updated_date'] = w.updated_date
        report['ns'] = w.name_servers
        report['admin_name'] = w.admin_name
        report['registrar'] = w.registrar
        return report

    def resolver(self):
        """
        This function will resolv the FQDN with different type of RR
        """
        report = dict()

        for t in self._rrtype.keys():
            report[t] = self._resolving(self._fqdn, t, self._rrtype[t])
        return report

    def _resolving(self, fqdn, t, attr):
        report = list()
        try:
            res_query = dns.resolver.resolve(fqdn, t)
            for rdata in res_query:
                if isinstance(attr, list):
                    data = dict()
                    for a in attr:
                        data[a] = getattr(rdata, a)
                    report.append(data)
                else:
                    report.append({
                        attr: getattr(rdata, attr)
                    })
        except dns.resolver.NoAnswer:
            pass
        except dns.resolver.NXDOMAIN:
            report.append({'error': 'Domain not exist'})
        except dns.resolver.NoNameservers:
            report.append({'error': 'Domain not exist'})
        return report

