//This file contains the RegistrationServer
//and RegistrationImpl implementations

package registration;

import java.sql.*;

import org.omg.CosNaming.*;
import org.omg.CORBA.*;
import java.util.ArrayList;

public class RegistrationServer extends _RegistrationHomeImplBase{

   ORB orb=null;
    
    static {
        try{
        new pool.JDCConnectionDriver("COM.cloudscape.core.JDBCDriver", 
		"jdbc:cloudscape:ejbdemo","none", "none");
        }catch(Exception e){ System.out.println("new pool error"+e);}
    }
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:jdc:jdcpool");
    }


    public RegistrationServer(ORB orb)  {
        super();
        this.orb=orb;
    }


    public registration.RegistrationPK create(String theuser, 
		String password, String emailaddress, String creditcard) 
		throws registration.CreateException{
        
        double balance=0;
        Connection con = null;
        PreparedStatement ps = null;;

        try {
           con=getConnection();
           ps=con.prepareStatement("insert into registration(
		theuser, password, emailaddress, creditcard, balance) 
		values (?, ?, ?, ?, ?)");
           ps.setString(1, theuser);
           ps.setString(2, password);
           ps.setString(3, emailaddress);
           ps.setString(4, creditcard);
           ps.setDouble(5, balance);
           
           if (ps.executeUpdate() != 1) {
               throw new CreateException ();
           }
           RegistrationPK primaryKey = new RegistrationPKImpl();
           primaryKey.theuser(theuser);
           return primaryKey;
       } catch (CreateException ce) {
          throw ce;
       } catch (SQLException sqe) {
          System.out.println("sqe="+sqe);
          throw new CreateException ();
       } finally {
          try {
             ps.close();
            con.close();
          } catch (Exception ignore) {
          }
       }
    }

    public registration.Registration findByPrimaryKey(
		registration.RegistrationPK pk) 
		throws registration.FinderException {
        if ((pk == null) || (pk.theuser() == null)) {
            throw new FinderException ();
        }
        return(refresh(pk));
    }

    private Registration refresh(RegistrationPK pk)
                      throws FinderException {

        if (pk == null) {
            throw new FinderException ();
        }
        Connection con = null;
        PreparedStatement ps = null;
        try {
           con=getConnection();
           ps=con.prepareStatement("select password, 
		emailaddress, creditcard, 
		balance from registration where theuser = ?");
           ps.setString(1, pk.theuser());
           ps.executeQuery();
           ResultSet rs = ps.getResultSet();
           if (rs.next()) {
              RegistrationImpl reg= new RegistrationImpl();
              reg.theuser = pk.theuser();
              reg.password = rs.getString(1);
              reg.emailaddress = rs.getString(2);
              reg.creditcard = rs.getString(3);
              reg.balance = rs.getDouble(4);
              return reg;
           }
           else {
               throw new FinderException ();
           }
       }
       catch (SQLException sqe) {
           throw new FinderException ();
       }
       finally {
          try {
             ps.close();
             con.close();
          }
          catch (Exception ignore) {}
       }
    }

    public void findLowCreditAccounts(final ReturnResults client)  
		throws FinderException {
        Runnable bgthread = new Runnable() {
           public void run() {
              Connection con = null;
              ResultSet rs = null;
              PreparedStatement ps = null;
              ArrayList ar = new ArrayList();

               try {
                    con=getConnection();
                    ps=con.prepareStatement("select theuser, 
			balance from registration where balance < ?");
                    ps.setDouble(1, 3.00);
                    ps.executeQuery();
                    rs = ps.getResultSet();
                    RegistrationImpl reg=null;
                    while (rs.next()) {
                        try {
                           reg= new RegistrationImpl();
                        }catch (Exception e) { 
                           System.out.println("creating reg"+e);
                        }
                        reg.theuser = rs.getString(1);
                        reg.balance = rs.getDouble(2);
                        ar.add(reg);
                    }
                    rs.close();
                      
                    RegistrationImpl[] regarray = (RegistrationImpl [])
				ar.toArray( new RegistrationImpl[0]);
                    client.updateResults(regarray);
                 }catch (Exception e) {
                     System.out.println("findLowCreditAccounts: "+e);
                     return;
                 }
                 finally {
                    try {
                       if(rs != null) {
                           rs.close();
                       }
                       if(ps != null) {
                           ps.close();
                       }
                       if(con != null) {
                           con.close();
                       }
                    } catch (Exception ignore) {}
                 }
             } //run
         };
         Thread t = new Thread(bgthread);
         t.start();
    }

    public Any customSearch(Any searchField, IntHolder count) {
        Any returnResults= orb.create_any();

        int tmpcount=count.value;
        if(searchField.type().kind().value() == TCKind._tk_double) {

            // return number of balances greater than supplied amount
            double findBalance=searchField.extract_double();
            Connection con = null;
            ResultSet rs = null;
            PreparedStatement ps = null;

            try {
                con=getConnection();
                ps=con.prepareStatement("select count(*) 
			from registration where balance < ?");
                ps.setDouble(1, findBalance);
                ps.executeQuery();
                rs = ps.getResultSet();
                if (rs.next()) {
                    tmpcount = rs.getInt(1);
                }
                count.value=tmpcount;
                rs.close();
             }catch (Exception e) {
                 System.out.println("custom search: "+e);
                 returnResults.insert_long(-1);
                 return(returnResults);
             }
             finally {
                try {
                   if(rs != null) {
                        rs.close();
                   }
                   if(ps != null) {
                        ps.close();
                   }
                   if(con != null) {
                        con.close();
                   }
                } catch (Exception ignore) {}
              }
            returnResults.insert_long(tmpcount);
            return(returnResults);

        } else if(searchField.type().kind().value() == 
				TCKind._tk_string) {

            // return email addresses that match supplied address
            String findEmail=searchField.extract_string();
            Connection con = null;
            ResultSet rs = null;
            PreparedStatement ps = null;
            ArrayList ar = new ArrayList();
            RegistrationImpl reg=null;

            try {
                con=getConnection();
                ps=con.prepareStatement("select theuser, 
			emailaddress from registration where emailaddress like ?");
                ps.setString(1, findEmail);
                ps.executeQuery();
                rs = ps.getResultSet();
                while (rs.next()) {
                    reg= new RegistrationImpl();
                    reg.theuser = rs.getString(1);
                    reg.emailaddress = rs.getString(2);
                    ar.add(reg);
                }
                rs.close();

                RegistrationImpl[] regarray = (RegistrationImpl 
			[])ar.toArray( new RegistrationImpl[0]);

                RegistrationHelper.insert(returnResults, regarray[0]);
                return(returnResults);
             }catch (Exception e) {
                 System.out.println("custom search: "+e);
                 return(returnResults);
             }
             finally {
                try {
                   if(rs != null) {
                        rs.close();
                   }
                   if(ps != null) {
                        ps.close();
                   }
                   if(con != null) {
                        con.close();
                   }
                } catch (Exception ignore) {}
              }
        }
        return(returnResults);

    }

   
    public static void main(String args[]) {

        java.util.Properties props=System.getProperties();
        props.put("org.omg.CORBA.ORBInitialPort", "1050");
        System.setProperties(props);

        ORB orb = ORB.init(args, props);

        RegistrationServer rs= new RegistrationServer(orb);
        try {
        orb.connect(rs);
        org.omg.CORBA.Object nameServiceObj = 
		orb.resolve_initial_references("NameService") ;
        NamingContext nctx= NamingContextHelper.narrow(nameServiceObj);
        NameComponent[] fullname = new NameComponent[2];
        fullname[0] = new NameComponent("auction", "");
        fullname[1] = new NameComponent("RegistrationBean", "");

        NameComponent[] tempComponent = new NameComponent[1];
        for(int i=0; i < fullname.length-1; i++ ) {
            tempComponent[0]= fullname[i];
            try {
                nctx=nctx.bind_new_context(tempComponent);
            }catch (Exception e){ System.out.println("bind new"+e);}
        }
        tempComponent[0]=fullname[fullname.length-1];
        try {
            nctx.rebind(tempComponent, rs);
        } catch (Exception e){ 
            nctx.unbind(tempComponent);
            nctx.rebind(tempComponent, rs);
             System.out.println("rebind"+e);
        }
        java.lang.Object sync= new java.lang.Object();
        synchronized(sync) {
           sync.wait();
        }
	} catch (Exception e) {
            System.out.println("e="+e);
        }
   }
}

class RegistrationImpl extends _RegistrationImplBase {
    public String theuser, password, creditcard, emailaddress;
    public double balance;

    public boolean verifyPassword(String password) {
        if (this.password.equals(password)) {
            return true;
        } else {
            return false;
        }
    }

    public String getEmailAddress() {
        return emailaddress;
    }

    public String getUser() {
        return theuser;
    }

    public int adjustAccount(double amount) {
        balance=balance+amount;
        return(0);
    }

    public double getBalance() {
        return balance;
    }
}
