package com.ociweb.JavaClient;

// create a runnable jar: http://stackoverflow.com/questions/1062941/build-project-into-a-jar-automatically-in-eclipse
// run as: java -jar JavaClient.jar
// orbd -ORBInitialPort 1050

import java.util.Iterator;
import java.util.Vector;

import org.apache.commons.cli.*;

import com.ociweb.JavaAddLib.AddClient;
import com.ociweb.JavaAddLib.Ref;

public class JavaClient {
	
	public static CommandLine ParseArgs(String[] args) {
		try {
			// http://commons.apache.org/cli/usage.html
			CommandLineParser parser = new PosixParser();
			Options options = new Options();
			options.addOption("?", "help", false, "print this message");
			options.addOption(null, "ORBInitialPort", true, "nameserver port (required)");
			options.addOption(null, "ORBInitialHost", true, "nameserver host");
			options.addOption( OptionBuilder.withLongOpt("add")
	                .withDescription( "two numbers to add (required)" )
	                .hasArgs(2)
	                .create());
			CommandLine line = parser.parse( options, args );
			
			if (line.hasOption("help") || !line.hasOption("add") || !line.hasOption("ORBInitialPort")) {
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp("Client", options);
				return null;
			}
			
			return line;
		} catch (ParseException e) {
			System.out.println(e.getMessage());
			return null;
		}
	}
	
	public static void main(String[] args) {
		CommandLine line = ParseArgs(args);
		if (line == null)
			return;
		
	    String[] opt = line.getOptionValues("add");
	    int x = Integer.parseInt(opt[0]);
	    int y = Integer.parseInt(opt[1]);
		
		AddClient c = new AddClient();
		c.init(args);
		
		Vector<Ref> refs = c.list();
		if (refs.size() == 0) 
			System.out.println("No servers found");
		else {
			Iterator<Ref> it = refs.iterator();
		    while(it.hasNext()) {
		    	Ref r = it.next();
		    	System.out.print(r.Name + ": ");
		    	try {
		    		System.out.println(c.add(r, x, y));
		    	} catch (Exception e) {
		    		System.out.println(e.getMessage());
		    	}
		    }
		}
		
		c.destroy();
	}

}
