import java.rmi.RemoteException;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import java.io.*;
/**
 * A simple client for accessing a Cart.
 */
public class ProductClient
{
	public static void main(String[] args)
	{
		try
		{
			/**
			 * Create access to the naming context.
			 */
			Context context = new InitialContext();

			/**
			 * Lookup the ProductHome object. The reference is retrieved from the
			 * application-local context (java:comp/env). The variable is
			 * specified in the assembly descriptor (META-INF/application-client.xml).
			 */
			Object homeObject = context.lookup("java:comp/env/MyProduct");

			// Narrow the reference to a ProductHome.
			ProductHome home = (ProductHome)PortableRemoteObject.narrow(homeObject, ProductHome.class);

			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

			System.out.print("Enter the id (integer) of the product you want to add: ");
			System.out.flush();
			int id = Integer.parseInt(in.readLine());

			System.out.print("Enter the name for item " + id + ": ");
			System.out.flush();
			String name = in.readLine();

			System.out.print("Enter the cost for " + name + ": ");
			System.out.flush();
			float cost = Float.parseFloat(in.readLine());

			// Create a new Product and narrow the reference.
			Product product = (Product)PortableRemoteObject.narrow(home.create(id), Product.class);
			product.setName(name);
			product.setPrice(cost);
			
			System.out.println("Product added");
		}
		catch(NumberFormatException e)
		{
			System.err.println("Invalid number specified");
		}
		catch(RemoteException e)
		{
			System.err.println("System/communication error: " + e.getMessage());
		}
		catch(IOException e)
		{
			System.err.println("IO Error: " + e.getMessage());
		}
		catch(NamingException e)
		{
			System.err.println("Communication error: " + e.getMessage());
		}
		catch(CreateException e)
		{
			System.err.println("Error creating cart: " + e.getMessage());
		}
	}
}
