/*
	QueryStarter.java
	Created by Tom Igoe on Tue Jun 22 2004.
	
	This is the main class for CoboxQuery.java.
	It opens a UDP socket, starts a UDP Listener thread, and
	listens for keyboard input. When it gets a lowercase 's',
	it calls CoboxQuery's sendQuery method and broadcasts a UDP query
	to the whole subnet. The listener thread listens for replies.

*/
import java.util.*;
import java.io.*;
import java.text.*;
import java.net.*;

public class QueryStarter {
 
 public static void main (String args[]) {
	DatagramSocket mainSocket = null;   // socket to send and receive on
	InetAddress localIp = null;			// address of the machine running program
	InetAddress broadcastIp;			// broadcast IP address for this subnet
	BufferedReader stdin;				// keyboard input

	//Print out to the command line:
	System.out.println ( "\n\nHello and Welcome to Cobox Discoverer" );
	System.out.println ( "Type  and  to kill the server\n\n");
    
	// start listening to the keyboard:
	stdin = new BufferedReader(new InputStreamReader(System.in));
	
	// get this machines IP address, or quit if it doesn't have one:
	try {
		localIp = InetAddress.getLocalHost();
	} catch (UnknownHostException uhe) {
		System.out.println(uhe);
		System.out.println("Quitting.");
		System.exit(0);
	}
	// if we're only a local loopback address (127.0.0.1), then quit:
	if (localIp.isLoopbackAddress()) {
		System.out.println("No connection to the network. Quitting.");
		System.exit(0);
	}
	//  open a UDP socket:
	try {
		mainSocket = new DatagramSocket();
	} catch (SocketException se) {System.out.println(se);}
	
	// open a CoboxQuery object with the socket:
	CoboxQuery myQuery = new CoboxQuery(mainSocket);
	// start a UDP listener thread with the socket:
	UdpListenerThread listener = new UdpListenerThread(mainSocket);
	// tell the user the local IP:
	System.out.println("Address of this machine: " + localIp + "\n");
	// get the broadcast address of this subnet:	
	broadcastIp = myQuery.getBroadcastAddress(localIp);
	
	// start the listener thread running:
	listener.start();	
	
	// as long as the listener's running, listen for keyboard input:
	while(listener.isAlive()) {
		try {
			// if there's anything from the keyboard, read it:
			if (stdin.ready()) {
				int inChar = stdin.read();
				// look for 'x' or 's':
				if (inChar == 0x78) {		//ASCII x; quit the program
					listener.kill();
					mainSocket.close();
				}
				if (inChar == 0x73) {		// ASCII s; send a query
					myQuery.sendQuery(broadcastIp);
				}
			} 
			
		} catch(IOException e) {System.out.println(e);}
		   try { Thread.sleep(10); } catch (InterruptedException interrupted) {}
	}
 }
}