package samples.marketplace;

import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

/**
 * See README for info.
 *
 * @author William A. Nagy <nagy@watson.ibm.com>
 */
public class BuyerSeller
{
  
  private static void printUsageAndTerminate()
  {
    System.err.println("Usage: java " + BuyerSeller.class.getName() +
			" SOAP-router-URL (buyer|seller) item price");
    System.exit(1);
  }

  public static void main(String[] args)
    throws Exception
  {
    if (args.length != 4)
    {
      printUsageAndTerminate();
    }
    
    // Process the arguments.
    URL url = new URL(args[0]);
    String mode = args[1];
    
    if ((!mode.equals("buyer")) && (!mode.equals("seller")))
    {
      printUsageAndTerminate();
    }
    
    String item = args[2];
    String price = args[3];
    
    // Build the call.
    Call call = new Call();
    Vector params = new Vector();
    if (mode.equals("buyer"))
    {
      call.setTargetObjectURI("urn:samples:marketplaceService#marketplaceServiceBP#buyer#urn:samples:marketplaceService#buyerPT");
      params.addElement(new Parameter("item", String.class, item, null));
      params.addElement(new Parameter("offer", Integer.class, new Integer(price), null));
    }
    else
    {
      call.setTargetObjectURI("urn:samples:marketplaceService#marketplaceServiceBP#seller#urn:samples:marketplaceService#sellerPT");
      params.addElement(new Parameter("inventoryItem", String.class, item, null));
      params.addElement(new Parameter("askingPrice", Integer.class, new Integer(price), null));
    }

    call.setMethodName("submit");
    call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
    call.setParams(params);
    
    // make the call: note that the action URI is empty because the 
    // XML-SOAP rpc router does not need this. This may change in the
    // future.
    Response resp = call.invoke(/* router URL */ url, /* actionURI */ "" );
    
    // Check the response.
    if (resp.generatedFault())
    {
      Fault fault = resp.getFault();
      System.out.println("Ouch, the call failed: ");
      System.out.println("  Fault Code   = " + fault.getFaultCode());  
      System.out.println("  Fault String = " + fault.getFaultString());
      System.out.println("  Fault        = " + fault);
    }
    else
    {
      Parameter result = resp.getReturnValue();
      System.out.println(result.getValue());
    }
  }
}
