import org.biomoby.client.CentralImpl;
import org.biomoby.client.MobyRequest;
import org.biomoby.shared.*;
import org.biomoby.shared.data.*;
import org.biomoby.shared.parser.ServiceException;

import java.net.*;
import java.util.Iterator;

/**
 * @author gordonp@ucalgary.ca
 *
 * A simple test program that build a base MobyObject, finds services at MOBY 
 * Central with it, then invokes a remote SeqHound service with it.
 */
public class MobyPinger{

    public static void main(String[] args) {
        long elapsedTimeMillis = 0;
        try{
            if(args.length != 2){
              System.err.println("Usage: java MobyPinger serviceName (serviceProviderURI|serviceEndpointURL)");
              System.exit(1);
            }
       
            Central worker = new CentralImpl ();
	    MobyService service = null;
	    try{
		String serviceURLString = (new URL(args[1])).toString();
		service = new MobyService(args[0]);
		service.setURL(serviceURLString);
	    }
	    catch(MalformedURLException murle){		
	    }
	    if(service == null){
		// Make template for finding services from the registry instead
		MobyService templateService = new MobyService(args[0]);
		templateService.setAuthority(args[1]);
		
		MobyService[] validServices = worker.findService(templateService);
		
		// Make sure we have a service to run for this input
		if(validServices == null || validServices.length == 0){
		    System.err.println("Could not find a valid service with name "+
				       args[0] + " and provider " + args[1]);
		    System.exit(1);
		}
		service = validServices[0];
	    }

	    MobyRequest mr = new MobyRequest(worker);

	    // Set input and run the service
	    mr.setService(service);
	    mr.setInput(new MobyContentInstance());  // blank request
            long startTimeMillis = System.currentTimeMillis();
	    MobyContentInstance responses = mr.invokeService();
            elapsedTimeMillis = System.currentTimeMillis()-startTimeMillis;

	    // Process responses
	    // The service invocation may have had many requests, there is a response
	    // object for each request
            for(ServiceException ex: responses.getExceptions()){
              if(ex.getSeverity() == ServiceException.ERROR){
                System.err.println("Exception in response from service: " + ex);
                System.exit(1);
              }
            }
	    if(responses.keySet().size() != 0){
              System.err.println("Response from service was not blank as expected:");
              MobyDataUtils.toXMLDocument(System.err, responses);
              System.exit(1);
	    }
	}catch(Exception e){
	    System.out.println("Problem while running ping: "+e);
            System.exit(1);
	}
        System.err.println("Ping successful, elapsed time for call was " + elapsedTimeMillis + "ms");
    }
} 
