import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import java.util.*;
import javax.ejb.*;

import myEJB.*;

public class Client
{
	Properties properties = null;
	InitialContext jndiContext = null;
	String newCabinName = null;

  public static void main(String[] args)
  {
	  if (args.length > 0)
	  {
	  	Client myApp = new Client(args[0]);
	  	myApp.runApp();
  	  }
  	  else
  	  {
		  System.out.println("Usage: Client Room-Name");
      }
  } // end main

  public Client(String aCabinName)
  {
    // preparing properties for constructing an InitialContext object
    properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    properties.setProperty(Context.PROVIDER_URL, "localhost");
    properties.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    newCabinName = aCabinName;
  }

  public void runApp()
  {
		try {
			// connect to JNDI
   			jndiContext = new InitialContext(properties);

      // Get a reference to the Bean
      		Object ref  = jndiContext.lookup("ejb/Cabin");
      		System.out.println("Got reference");

      // Get a reference from this to the Bean's Home interface
      		CabinHomeRemote home = (CabinHomeRemote)
        		PortableRemoteObject.narrow (ref, CabinHomeRemote.class);

			CabinBeanDAO insertRow = new CabinBeanDAO();
			makeRow(insertRow);

      // insert a row and get a Reference to the Remote Interface
      		CabinRemote cr = home.create(insertRow);

      		listAllRows(home);

      		System.out.println ("check database for new Row");

    	}
    	catch(Exception e)
    	{
      		System.out.println(e.toString());
    	}
  }

  private void makeRow(CabinBeanDAO newRow)
  {
	  newRow.shipId  = new Integer(1);
	  newRow.cabinName = newCabinName;
	  newRow.bedCount = 5;
	  newRow.deckLevel = 20;
	  newRow.createUser = new String("Joe");
	  newRow.createTime = null;
	  newRow.lastUpdateUser = null;
	  newRow.lastUpdateTime = null;
	  newRow.sold = null;
  }

  private void listAllRows(CabinHomeRemote homeRef)
  {
	  	CabinBeanDAO rowData = null;
	  	CabinRemote remoteRef = null;

	  	try {
			System.out.println("\n");
			Collection beanList = homeRef.findByShipId(new Integer(1));
			Iterator beanIterator = beanList.iterator();
			while(beanIterator.hasNext())
			{
				remoteRef = (CabinRemote) beanIterator.next();
				rowData = remoteRef.getRow();
				System.out.println(rowData.shipId.toString() + ":" + rowData.cabinName);
			}
			System.out.println("\n");
  		}
  		catch(Exception e)
  		{
			System.out.println("Network or Database Down");
		}
  }
}

