
import org.smapcore.smap.core.*;
import org.smapcore.smap.core.server.*;


public class SMAPer {
    
    private String impl = "org.smapcore.smap.transport.beep";
    private String server = null;
    private int port = 0;
    private SMAPServer smap;


    public SMAPer(String server, int port)
	throws Exception {
	
	this.port = port;
	
	this.smap = new SMAPServer(this.impl, this.server, this.port);
    }


    public SMAPer(String impl, String server, int port)
	throws Exception {
	
	if (impl != null) {
	    this.impl   = impl;
	}

	this.port   = port;
	
	this.smap = new SMAPServer(this.impl, this.server, this.port);
    }


    public void start() 
	throws Exception {

	this.smap.start();
	return;
    }


    public static void main(String[] args) {
	
	String impl  = null;
	String host  = null;
	String server;
	int port = 0;

	for (int i = 0; i < args.length; i++) {
	    
	    if (args[i].equalsIgnoreCase("-i")) {
		if (++i == args.length) {
		    usage();
		    System.exit(1);
		}
		
		impl = args[i];
	    } else {
		if (host != null) {
		    usage();
		    System.exit(1);
		}

		host = args[i];
	    }
	}

	if (host == null) {
	    usage();
	    System.exit(1);
	}

	int pos = host.indexOf(':');
	if (pos < 0) {
	    server = host;
	} else if (pos > 0) {
	    server = host.substring(0, pos);
	    try {
		port = Integer.parseInt(host.substring(pos+1));
	    } catch (NumberFormatException nfe) {
		System.err.println("unable to parse server:port");
		System.exit(1);
		return;
	    }
	} else {
	    System.err.println("unable to parse server:port");
	    System.exit(1);
	    return;
	}

	SMAPer smaper;

	try {
	    smaper = new SMAPer(impl, server, port);
	    smaper.start();
	} catch (Exception e) {
	    System.err.println("unable to start SMAP server " + e.getMessage());
	    Throwable t = e.getCause();
	    while (t != null) {
		System.err.println("\t " + t.getMessage());
		t = t.getCause();
	    }
	    e.printStackTrace();
	    System.exit(1);
	    return;
	}
    }


    private static void usage() {

	System.out.println("usage: " + SMAPer.class.getName() + " <host>[:<port>]");
	System.out.println("\t\t -i <impl>        transport implementation");

	return;
    }
}
