package de.hsadmin.core.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import de.hsadmin.core.model.HSAdminException;
import de.hsadmin.core.util.dns.DNSQuery;
import de.hsadmin.core.util.dns.DNSService;


public class DNSCheck {

	private String dnsServer;
	
	public DNSCheck(String dnsServer) throws HSAdminException {
		this.dnsServer = dnsServer;
		InetAddress dnsInetAddress;
		try {
			dnsInetAddress = InetAddress.getByName(dnsServer);
			DNSService.SetDNSAddress(dnsInetAddress);
		} catch (UnknownHostException e) {
			throw new HSAdminException(e);
		}
	}
	
	public boolean checkDomain(String domain) throws HSAdminException {
		boolean hasNSRecord = false;
		boolean hasARecord = false;
		DNSQuery dnsQuery = new DNSQuery();
		dnsQuery.SetQuery(DNSQuery.TYPE_NS, DNSQuery.CLASS_INTERNET, domain);
		if (DNSService.PerformDNSQuery(dnsQuery)) {
			hasNSRecord = dnsQuery.getDNSAuthorityRecords() != null && dnsQuery.getDNSAuthorityRecords().length > 0;
			if (dnsQuery.getDNSAuthorityRecords() != null) {
				System.out.println("NS:" + dnsQuery.getDNSAuthorityRecords().length);
			}
		} else {
			throw new HSAdminException("domain " + domain + " is not delegated to " + dnsServer);
		}
		dnsQuery.SetQuery(DNSQuery.TYPE_A, DNSQuery.CLASS_INTERNET, domain);
		if (DNSService.PerformDNSQuery(dnsQuery)) {
			hasARecord = dnsQuery.getDNSAnswerRecords() != null && dnsQuery.getDNSAnswerRecords().length > 0;
			if (dnsQuery.getDNSAnswerRecords() != null) {
				System.out.println("A: " + dnsQuery.getDNSAnswerRecords().length);
			}
		} else {
			throw new HSAdminException("domain " + domain + " is not delegated to " + dnsServer);
		}
		return hasNSRecord & !hasARecord;
	}
}
