package ejava.examples.personnel.ejb20; 

import ejava.examples.personnel.Person;
import ejava.examples.uid.ejb.UIDGeneratorLocalHome;
import ejava.examples.uid.ejb.UIDGeneratorLocal;
import ejava.examples.uid.ejb.UID;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.ejb.EJBException;
import javax.rmi.PortableRemoteObject;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;

public class RegistrarEJB implements RegistrarBI, SessionBean {
   PersonLocalHome pHome_;
   UIDGeneratorLocal uidGenerator_;

   /**
      Generates a uid and adds the person to the database.
   */
   public Person add(Person person)
		     throws PersonnelException {
      try {
         UID uid = uidGenerator_.createUID();
	 PersonLocal newPerson = pHome_.create(uid.toString(),
	    person.getFirstName(), 
	    person.getLastName(),
	    person.getAddress(),
	    person.getPhoneNumber());
         
         return new Person(newPerson.getId(),
	                   newPerson.getFirstName(), 
	                   newPerson.getLastName(),
	                   newPerson.getAddress(),
	                   newPerson.getPhoneNumber());
      }
      catch (CreateException ex) {
         throw new PersonnelException(ex.toString());
      }
      catch (Exception ex) {
         throw new EJBException("unable to create person:"+ex);
      }
   }

   public void ejbCreate() {}
   public void ejbActivate() {}
   public void ejbPassivate() {}
   public void ejbRemove() {}

   private SessionContext sessionCtx_;
   public void setSessionContext(SessionContext sessionCtx) 
      throws RemoteException {

      sessionCtx_ = sessionCtx;
      try {
         InitialContext ctx = new InitialContext();
	 Object object = ctx.lookup("java:comp/env/ejb/PersonLocalHome");
         pHome_ = (PersonLocalHome)
	    PortableRemoteObject.narrow(object, PersonLocalHome.class);

         object = ctx.lookup("java:comp/env/ejb/UIDGeneratorLocalHome");
	 UIDGeneratorLocalHome uidHome_ = (UIDGeneratorLocalHome)
	    PortableRemoteObject.narrow(object, UIDGeneratorLocalHome.class);
         uidGenerator_ = uidHome_.find();
      }
      catch (FinderException ex) {
         throw new EJBException("uid generator not located;"+ex);
      }
      catch (NamingException ex) {
         throw new EJBException("error locating ejb objects:"+ ex);
      }
      finally {
      }
   }
}
