package de.hsadmin.core.util.dns;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;


public class DNSService {

	public static int DNS_SOCKET = 53;
	private static InetAddress m_iaDNS = null;
	private static Socket m_sockService = null;
	private static byte[] m_abReceive = new byte[512];

	private static int m_iQuerySerial = 0x1234;

	public static void SetDNSAddress(InetAddress iaDNS) {
		m_iaDNS = iaDNS;

		if (m_sockService == null) {
			try {
				m_sockService = new Socket(m_iaDNS, DNS_SOCKET, false);
			} catch (IOException ioe) {
				System.err.println("exception: " + ioe.getMessage());
			}
		}
	}

	public static boolean PerformDNSQuery(DNSQuery dns) {
		if (m_iaDNS == null || dns == null) {
			return false;
		}

		ByteArrayOutputStream bas = new ByteArrayOutputStream();

		dns.WriteQuery(bas);
		
		try {
			m_sockService.getOutputStream().write(bas.toByteArray());
		} catch (IOException ioe) {
			return false;
		}

		try {
			BufferedInputStream bis = new BufferedInputStream(m_sockService.getInputStream(), 512);

			int cRetry = 5;
			int cbAvail = 0;
			
			while (cRetry-- > 0 && ((cbAvail = bis.available()) <= 0)) {
				try {
					Thread.currentThread().sleep(200);
				} catch (InterruptedException ie) {	
					System.err.println("exception: " + ie.getMessage());
				}
			}
			
			if (cbAvail > 0) {
				int cbRead = bis.read(m_abReceive, 0, cbAvail);
			
				m_iQuerySerial++;

				if (cbRead > 0) {
					dns.ReadQuery(m_abReceive, cbRead);
				} else {
					return false;
				}
			} else {
				return false;
			}
		} catch (IOException ioe) {
			return false;
		}
		
		return true;
	}

}
