import java.io.*;
import java.util.*;
import java.net.*;
import rsvcClient;
import rsvcEventHandler;
import rsvcConfig;

public final class rsvcServerTest implements rsvcEventHandler
{
    public rsvcServerTest ()
    {
	// empty
    }

    public static void main (String[] args) 
    {
	if (args.length < 4) {
	    System.err.println ("Usage: rsvcServerTest name domain host port");
	    System.exit (-1);
	}

	rsvcServerTest test = new rsvcServerTest ();

	String host = args[2];
	int port = Integer.valueOf (args[3]).intValue();
	int udpport = port + 1024;
	String server = args[0];
	String domain = args[1];

	rsvcData serverinfo = new rsvcData ();
	rsvcData udpinfo = new rsvcData ();

	serverinfo.insert ("name", server);
	serverinfo.insert ("domain", domain);
	serverinfo.insert ("host", host);
	serverinfo.insert ("owner", "chen");
	serverinfo.insert ("time", (int)(System.currentTimeMillis()/1000));
	serverinfo.insert ("port", (int)(System.currentTimeMillis()%65535));
	serverinfo.insert ("pid", (int)1234);

	udpinfo.insert ("name", server);
	udpinfo.insert ("domain", domain);
  
	rsvcClient client = new rsvcClient ();
	rsvcUdpClient udpclient = new rsvcUdpClient();

	try {
	    client.connect (host, port);
	}catch (UnknownHostException ue) {
	    System.err.println (ue);
	    System.exit (-1);
	}catch (IOException e) {
	    System.err.println (e);
	    System.exit (-1);
	}

	try {
	    udpclient.connect (host, udpport);
	}catch (UnknownHostException ue) {
	    System.err.println (ue);
	    System.exit (-1);
	}catch (IOException e) {
	    System.err.println (e);
	    System.exit (-1);
	}


	// outbound event stream
	rsvcEvent oevent = null;
	try {
	    oevent = client.insertValue ("cdevServers", serverinfo,
					 test, true);
	}catch (IOException e) {
	    System.err.println (e);
	    System.exit (-1);
	}
	
	
	Thread readerThread = client.getReaderThread ();

	while (true) {
	    try {
		udpclient.update (udpinfo);
	    } catch (IOException e) {
		System.err.println (e);
		System.exit (-1);
	    }

	    // wait for 5 seconds
	    try {
		readerThread.join (5000);
	    } catch (InterruptedException e) {
		System.err.println (e);
		System.exit (-1);
	    }
	}
    }

    public void handleEvent (rsvcEvent event)
    {
	int status = event.getStatus ();
	int opcode = event.getOpcode ();
	rsvcData data = event.getData ();

	System.out.println ("Handle event is called with status :" + String.valueOf (status));
	
	switch (opcode) {
	case rsvcConfig.RSVC_GET:
	    System.out.println ("Get Value with result :");
	    break;
	case rsvcConfig.RSVC_QUERY:
	    System.out.println ("Query Value with result :");
	    break;
	case rsvcConfig.RSVC_SET:
	    System.out.println ("Set Value with result :");
	    break;	    
	default:
	    System.out.println ("Operation : " + String.valueOf (opcode));
	}

	if (status == rsvcConfig.RSVC_NOTFOUND)
	    System.out.println ("Found nothing");

	if (status == rsvcConfig.RSVC_SUCCESS)
	    data.asciiDump ();
    }
}
