package search;

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 java.sql.*;

public class SearchBean implements SessionBean {

    protected SessionContext sctx;
    Properties p = new Properties();
    Context ctx;

    static {
        new weblogic.jdbc.jts.Driver();
    }

    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:weblogic:jts:ejbPool");
    }

    public Enumeration getMatchingItemsList(String searchString) 
		throws RemoteException {

        ResultSet rs = null;
        PreparedStatement ps = null;
	Vector v = new Vector();
        Connection con = null;

        try{
           AuctionItemHome home = (AuctionItemHome) 
		ctx.lookup("auctionitems");
           con=getConnection();
           ps=con.prepareStatement(
		"select id from auctionitems where summary like ?");
           ps.setString(1, "%"+searchString+"%");
           ps.executeQuery();
           rs = ps.getResultSet();
           AuctionItemPK pk;
           while (rs.next()) {
               pk = new AuctionItemPK();
               pk.id = (int)rs.getInt(1);
	       v.addElement(pk);
           }
	   rs.close();
	   return v.elements();

        }catch (Exception e) {
	    System.out.println("getMatchingItemsList: "+e);
	    return null;
        }
        finally {
           try {
	      if(rs != null) {
                 rs.close();
              }
	      if(ps != null) {
                 ps.close();
              }
	      if(con != null) {
                 con.close();
              }
          } catch (Exception ignore) {}
        }
    }


    public void ejbCreate() 
		throws CreateException, RemoteException {
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY, 
		"weblogic.jndi.TengahInitialContextFactory");
        try{
	    ctx = new InitialContext(p);
        }catch(Exception e) {
	    System.out.println("create exception: "+e);
	}
    }

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

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

    public void ejbRemove() {}
    public void ejbActivate() throws RemoteException { }
    public void ejbPassivate() throws RemoteException { }
}
