package seller;

import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.*;
import java.text.NumberFormat;
import java.io.Serializable;
import javax.naming.*;
import auction.*;
import registration.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;


public class SellerBean extends _ReturnResultsImplBase 
		implements SessionBean {

    protected SessionContext ctx;
    javax.naming.Context ectx;
    Hashtable env = new Hashtable();
    ORB orb = null;
    NamingContext nctx= null;
    Boolean ready=new Boolean("false");
    ArrayList returned =new ArrayList();


    public int insertItem(String seller, String password, 
		String description, int auctiondays, 
		double startprice, String summary) 
		throws RemoteException { 

        try{
        NameComponent[] fullname = new NameComponent[2];
        fullname[0] = new NameComponent("auction", "");
        fullname[1] = new NameComponent("RegistrationBean", "");

        RegistrationHome regRef = RegistrationHomeHelper.narrow(
		nctx.resolve(fullname));
        RegistrationPK rpk= new RegistrationPKImpl();
        rpk.theuser(seller);
        Registration newseller = RegistrationHelper.narrow(
		regRef.findByPrimaryKey(rpk));
	if((newseller == null)|| (!newseller.verifyPassword(password))) {
            return(Auction.INVALID_USER);	
	}

        AuctionItemHome home = (AuctionItemHome) ectx.lookup("auctionitems");
        AuctionItem ai= home.create(seller, description, 
			auctiondays, startprice, summary);
	if(ai == null) {
           return Auction.INVALID_ITEM;
	} 
	else {
           return(ai.getId()); 
	}

        }catch(Exception e){ 
           System.out.println("insert problem="+e);
           return Auction.INVALID_ITEM;
        }
    }

    public void updateResults(Registration[] ar) 
		throws registration.FinderException {
       if(ar == null) {
          throw new registration.FinderException();
       }
       try {
          for(int i=0; i< ar.length; i++) {
             returned.add(ar[i]);
          }
       }catch (Exception e) {
           System.out.println("updateResults="+e);
           throw new registration.FinderException();
       }
       synchronized(ready) {
          ready.notifyAll();
       }
    }

    public ArrayList auditAccounts() {
        try {
            NameComponent[] fullname = new NameComponent[2];
            fullname[0] = new NameComponent("auction", "");
            fullname[1] = new NameComponent("RegistrationBean", "");

            RegistrationHome regRef = 
		RegistrationHomeHelper.narrow(nctx.resolve(fullname));
            regRef.findLowCreditAccounts(this);
            synchronized(ready) {
              try {
                 ready.wait();
              } catch (InterruptedException e){}
            }
           return (returned);
        }catch (Exception e) {
           System.out.println("error in auditAccounts "+e);
        }
        return null;
    }


    public String customFind(String searchField) 
		throws javax.ejb.FinderException, RemoteException{

        int total=-1;
        IntHolder count= new IntHolder();

        try{
        NameComponent[] fullname = new NameComponent[2];
        fullname[0] = new NameComponent("auction", "");
        fullname[1] = new NameComponent("RegistrationBean", "");

        RegistrationHome regRef = 
		RegistrationHomeHelper.narrow(nctx.resolve(fullname));
        if(regRef == null ) {
           System.out.println("cannot contact RegistrationHome");
           throw new javax.ejb.FinderException();
        }
        Any sfield=orb.create_any();
        Double balance;
        try {
           balance=Double.valueOf(searchField);
           try {
              sfield.insert_double(balance.doubleValue());
           } catch (Exception e) {
              return("Problem with search value"+balance);
           }
           sfield=regRef.customSearch(sfield,count);
           if (sfield != null ) {
              total=sfield.extract_long();
           }
           return(total+" accounts are below optimal level");
        } catch (NumberFormatException e) {
           sfield.insert_string(searchField);
           Registration reg;
           if((reg=RegistrationHelper.extract(
		regRef.customSearch(sfield,count))) != null ) { 
               return("Found user "+reg.getUser()+
		" who has email address "+reg.getEmailAddress());
           } else {
               return("No users found who have email address "+searchField);
           }
        }
        
        } catch(Exception e){
           System.out.println("customFind problem="+e);
           throw new javax.ejb.FinderException();
        }
    }




    public void ejbCreate() throws javax.ejb.CreateException, RemoteException {
        env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, 
		"weblogic.jndi.TengahInitialContextFactory");
        try {
            ectx = new InitialContext(env);
        } catch (NamingException e) {
            System.out.println("problem contacting EJB server");
            throw new javax.ejb.CreateException();
        }
        try {
           java.util.Properties props=System.getProperties();
           props.put("org.omg.CORBA.ORBInitialPort", "1050");
           System.setProperties(props);
           String[] args={};
           orb = ORB.init(args, props);

           org.omg.CORBA.Object nameServiceObj = 
		orb.resolve_initial_references("NameService") ;
           nctx= NamingContextHelper.narrow(nameServiceObj);
        } catch(org.omg.CORBA.SystemException e) {
            throw new javax.ejb.CreateException("CORBA Error in SellerCreate "+e);
        } catch ( org.omg.CORBA.ORBPackage.InvalidName e) {
            throw new javax.ejb.CreateException("CORBA NameError in SellerCreate "+e);
        }
    }

    public void setSessionContext(SessionContext ctx) throws RemoteException {
        this.ctx = ctx;
    }

    public void unsetSessionContext() throws RemoteException {   
        ctx = null;  
    } 

    public void ejbRemove() {}
    public void ejbActivate() throws RemoteException {
	System.out.println("activating seller bean");
    }
    public void ejbPassivate() throws RemoteException { 
	System.out.println("passivating seller bean");
    }
}


