/* Author: Jeff Dalton <J.Dalton@ed.ac.uk>
 * Updated: Sun May 27 21:57:01 2001 by Jeff Dalton
 * Copyright: (c) 2001, AIAI, University of Edinburgh
 */

package ix.test;

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

import ix.util.lisp.*;

import ix.util.*;

public class LowLevelIPCTest {

    public static void main(String[] argv) {

	Parameters.processCommandLineArguments(argv);

	int serverPort = Parameters.getInt("server.port", -1);
	int clientPort = Parameters.getInt("client.port", -1);

	Parameters.checkParameterUse();

	try {

	    // Set up server side if a server.port was specified
	    if (serverPort > -1) {
		final ServerSocket servSock = new ServerSocket(serverPort);

		new Thread() {
		    public void run() {
			while (true) {
			    handleClient(servSock);
			}
		    }
		}.start();
	    }

	    // Set up client side if a client.port was specified.
	    if (clientPort > -1) {
		IPC.ObjectStreamConnection connection = null;
		while(true) {
		    final String text = Util.askLine("Send: ");
		    if (connection == null) {
			Socket s = new Socket("localhost", clientPort);
			connection = new IPC.ObjectStreamConnection(s);
		    }
		    Serializable closure = new Serializable() {
			public String toString() {
			    return "Enclosed string = " + Util.quote(text);
			}
		    };
		    // See what amazing things we can send.
		    connection.send(closure);
		    connection.send(Lisp.list());
		    connection.send(Lisp.list(text, Symbol.intern(text)));
		    LListCollector col = new LListCollector();
		    col.add("c1");
		    col.add(text);
		    connection.send(col);
		}
	    }

	}
	catch (Exception e) {
	    Debug.noteException(e);
	}

    }

    static void handleClient(final ServerSocket servSock) {
	try {
	    Socket s = servSock.accept();
	    Debug.noteln("Client connection", s);
	    final IPC.ObjectStreamConnection c
		= new IPC.ObjectStreamConnection(s);
	    new Thread() {
		public void run() {
		    Debug.noteln("Listener running ...");
		    try {
			while (true) {
			    Debug.noteln("Waiting to receive ...");
			    Debug.noteln("Received", c.receive());
			}
		    }
		    catch (Exception e) {
			Debug.noteException(e);
		    }
		}
	    }.start();
	}
	catch (Exception e) {
	    Debug.noteException(e);
	}
    }

}
