/*
 *
 * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * This software is the proprietary information of Sun Microsystems, Inc.  
 * Use is subject to license terms.
 * 
 */


package ejb.users;

import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
import java.rmi.*;
import utils.*;
import ejb.dataAccess.*;




public class UserEJB implements EntityBean {


    private String name;
    private String email;
    private Timestamp lastVisited;
    private long totalTimeSpent;

    private EntityContext context;
    private Data dataAccess;
    private String dbName = ServerConstants.usersDB;
            //"java:comp/env/jdbc/Users";
    private String dataAccessSessionBean = ServerConstants.dataAccessBean;
            //"java:comp/env/ejb/DataAccessBean";



    public String ejbCreate(String name,String email,Timestamp lastVisited,long totalTimeSpent)
                                throws CreateException {


        int numOfRows = 0;

        try {

            numOfRows = insertRow(name,email,lastVisited,totalTimeSpent);

        } //try

        catch (Exception ex) {

            throw new EJBException("UserEJB.ejbCreate(): " + 
                ex.getMessage());

        } //catch (Exception ex)

        this.name = name;
        this.email = email;
        this.lastVisited = lastVisited;
        this.totalTimeSpent = totalTimeSpent;

        return email;

    }





   public String ejbFindByPrimaryKey(String email) 
      throws FinderException {

      boolean result = false;

      try {
         result = selectByPrimaryKey(email);
       } catch (Exception ex) {
           throw new EJBException("User.ejbFindByPrimaryKey(): " + 
              ex.getMessage());
       }

      if (result) {
         return email;
      }

      else if(!result) {

        return null;

      } //else if(!result)

      else {
         throw new ObjectNotFoundException
            ("User.findByPrimaryKey(), Row for email " + email + " not found.");
      }
   }








   public Collection ejbFindAll()
      throws FinderException {

      Collection result = new ArrayList();

      try {
         result = selectAll();
            
       } catch (Exception ex) {
           throw new EJBException("User.ejbFindAll(): " + 
              ex.getMessage());
       }
      if (result.isEmpty()) {
         //throw new ObjectNotFoundException("User.ejbFindAll(), No rows found.");
         result = new ArrayList();
         return result;
      }
      else {
         return result;
      }
   }



/**
   public Collection ejbFindInRange(String start,String end)
      throws FinderException {

      Collection result;

      try {
         result = selectInRange(start, end);
            
       } catch (Exception ex) {
           throw new EJBException("ejbFindInRange: " + 
              ex.getMessage());
       }
      if (result.isEmpty()) {
         throw new ObjectNotFoundException("No rows found.");
      }
      else {
         return result;
      }
   }
**/








   public void ejbRemove() {

      try {
         deleteRow(email);
       } catch (Exception ex) {
           throw new EJBException("User.ejbRemove(): " + 
              ex.getMessage());
       }
   } 






    public void setEntityContext(EntityContext context) {

        this.context = context;

        try {

            Context initial = new InitialContext();
            Object objref = initial.lookup(dataAccessSessionBean);

            DataHome home = 
                (DataHome)PortableRemoteObject.narrow(objref, 
                                            DataHome.class);

            dataAccess = home.create();


        } //try

        catch(NamingException e) {

            System.out.println("UserEJB.setEntityContext(), NamingException : " + e.toString());
            e.printStackTrace();
            System.exit(0);

        } //catch(NamingException e)


        catch(RemoteException re) {

            System.out.println("UserEJB.setEntityContext(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)


        catch(CreateException re) {

            System.out.println("UserEJB.setEntityContext(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)



   }//public void setEntityContext(EntityContext context)






    public void unsetEntityContext() {

        dataAccess = null;

    } //public void unsetEntityContext()





    public void ejbActivate() {

        email = (String)context.getPrimaryKey();

    }//public void ejbActivate()






   public void ejbPassivate() {

      email = null;

   }//public void ejbPassivate()






    public void ejbLoad() {

        try {
            loadRow();
        } //try

        catch (Exception ex) {
           throw new EJBException("User.ejbLoad(): " + 
              ex.getMessage());
        } //catch (Exception ex)
    }
   






   public void ejbStore() {

        try {
           storeRow();
        }//try

        catch (Exception ex) {
            throw new EJBException("User.ejbStore(): " + 
                ex.getMessage());
        }//catch (Exception ex)

    }//public void ejbStore()






    public void ejbPostCreate(String name,String email,Timestamp lastVisited,long totalTimeSpent) { }



/*********************** Business Methods *************************/




    public String getName() {

        return name;

    } //public String getName()



    public String getEmail() {

        return email;

    } //public String getEmail()



    public Timestamp getLastVisited() {

        return lastVisited;

    } //public Timestamp getLastVisited()



    public long getTotalTimeSpent() {

        return totalTimeSpent;

    } //public long getTotalTimeSpent()



    public void setName(String s) {

        this.name = s;

    } //public void setName(String s)


    public void setEmail(String s) {

        this.email = s;

    } //public void setEmail(String s)


    public void setLastVisited(Timestamp t) {

        this.lastVisited = t;

    } //public void setLastVisited(Timestamp t)


    public void setTotalTimeSpent(long l) {

        this.totalTimeSpent = l;

    } //public void setTotalTimeSpent(long l)



/**
    public int updateTotalTimeSpent(long t) {

        int numOfRows = 0;

        try {

            numOfRows = updateTimeSpent(email,t);

        } //try

        catch(java.sql.SQLException e) {

            throw new EJBException("User.updateTotalTimeSpent(): " + 
                e.getMessage());

        } //catch(java.sql.SQLException e)


        return numOfRows;

    } //public int updateTotalTimeSpent(long t)

**/



/*********************** Database Routines *************************/


    private int insertRow (String name,String email,Timestamp lastVisited,long totalTimeSpent)
                        throws SQLException {


        int numOfRows = 0;

        String sql = "insert into " + ServerConstants.iDSSUsersTable +
                    "(name,email,lastVisited,totalTimeSpent) values " + 
                    "(" +
                    "'" + name + "'" + "," +
                    "'" + email + "'" + "," +
                    "'" + lastVisited.toString() + "'" + "," +
                    "" + totalTimeSpent +")";

        try {

            numOfRows = dataAccess.insert(sql,dbName);

        } //try

        catch(RemoteException re) {

            System.out.println("UserEJB.insertRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            //System.exit(0);

        } //catch(RemoteException re)

        return numOfRows;

   } //private int insertRow (....)





    private void deleteRow(String email) throws SQLException {

        String deleteStatement = "delete from " + ServerConstants.iDSSUsersTable +
                                    " where email='" + email + "'";

        try {
            dataAccess.delete(deleteStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("UserEJB.deleteRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)

    } //private void deleteRow(String email) throws SQLException




    private boolean selectByPrimaryKey(String email) 
                                        throws SQLException {

        boolean result = false;

        String selectStatement = "select email from " + ServerConstants.iDSSUsersTable +
                                    " where email='" + email + "'";

        try {
            DataSet ds = dataAccess.select(selectStatement,dbName);

            Vector rows = ds.getRowsOfDataVector();

            if(rows.size() > 0)
                result = true;

            return result;


        } //try

        catch(RemoteException re) {

            System.out.println("UserEJB.selectByPrimaryKey(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)

        return result;

    } //private boolean selectByPrimaryKey(String email) 








    private Collection selectAll() throws SQLException {


        String selectStatement = "select * from " + ServerConstants.iDSSUsersTable;

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("UserEJB.selectAll(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)




        ArrayList a = new ArrayList();

        Vector rows = ds.getRowsOfDataVector();

        for(int i=0;i<rows.size();i++) {

            Vector oneRow = (Vector)rows.elementAt(i);
            String email = (String)oneRow.elementAt(1);
            a.add(email);

        } //for(int i=0;i<rows.size();i++)

        return a;

   } //private Collection selectAll()














/**

    private int updateTimeSpent(String email,long t) 
                                        throws SQLException {

        int numOfRows = 0;

        String updateStatement = "update " + ServerConstants.iDSSUsersTable + " set " +
                                "totalTimeSpent=" + t + " where email='" + email + "'";


        try {

            numOfRows = dataAccess.update(updateStatement,dbName);

        }

        catch(RemoteException re) {

            System.out.println("UserEJB.updateTimeSpent(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)

        return numOfRows;

   } //private int updateTimeSpent(String email,long t)

**/


    private void loadRow() throws SQLException {


        String selectStatement =
            "select name,email,lastVisited,totalTimeSpent from " + ServerConstants.iDSSUsersTable +
            " where email='" + email + "'";

        DataSet ds = null;

        try {
            ds = dataAccess.select(selectStatement,dbName);
        }

        catch(RemoteException re) {

            System.out.println("UserEJB.loadRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)



        Vector rows = ds.getRowsOfDataVector();

        if(rows.size() > 0) {

            Vector oneRow = (Vector)rows.elementAt(0);

            this.name = (String)oneRow.elementAt(0);
            this.email = (String)oneRow.elementAt(1);
            this.lastVisited = (Timestamp)oneRow.elementAt(2);
            this.totalTimeSpent = Long.parseLong((oneRow.elementAt(3).toString()));

        } //if(rows.size() > 0)

        else {

            throw new NoSuchEntityException("User.loadRow(), Row for email " + email +
                    " not found in database.");


        } //else



    } //private void loadRow() throws SQLException








    private void storeRow() throws SQLException {


        String updateStatement = "update " + ServerConstants.iDSSUsersTable + " set " +
                            "name='" + name + "'," +
                            "email='" + email + "'," +
                            "lastVisited='" + lastVisited.toString() + "'," +
                            "totalTimeSpent='" + totalTimeSpent + "'" +
                            " where email='" + email + "'";



        try {
            int rowCount = dataAccess.update(updateStatement,dbName);

            if (rowCount == 0) {

                throw new EJBException("User.storeRow(), storing row for email " + email + " failed.");

            } //if (rowCount == 0)

        } //try


        catch(RemoteException re) {

            System.out.println("UserEJB.storeRow(), RemoteException : " + re.toString());
            re.printStackTrace();
            System.exit(0);

        } //catch(RemoteException re)



    }//private void storeRow() throws SQLException 


} // UserEJB

