package damanPay.pay;
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.ejb.FinderException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.SessionSynchronization;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import grace.log.Log; 
import java.sql.*;
import javax.sql.DataSource;


import damanPay.business.*;
import damanPay.employee.*;
import damanPay.pay.*;

import java.math.BigDecimal;


public class VariationsImpl implements SessionBean{

    protected SessionContext sessionContext = null;
    public Context initialContext = null;
    InitialContext initCtx;
    BusinessUnitHome buHome;
    StubHome stubHome;
    EmployeeHome empHome;
    DamanNode root = null;
    DataSource dataSource = null;
    Connection con = null;
    int noPayPeriods;
    int payPeriod;
    int empOID;
    public void  ejbCreate() throws RemoteException { 
        try{
            initCtx = (InitialContext)getInitialContext();
	        buHome= (BusinessUnitHome)initCtx.lookup("BusinessUnitHome");
	        stubHome= (StubHome)initCtx.lookup("StubHome");
	        empHome= (EmployeeHome)initCtx.lookup("EmployeeHome");
	        Properties env = sessionContext.getEnvironment();
	        String dataSourceName = env.getProperty("datasource.name");
		    dataSource = (DataSource)initCtx.lookup(dataSourceName);
	        con = dataSource.getConnection();
		    
	        
            
        }catch (Exception e){
            throw new RemoteException(e.toString());
        }    
    }

    /*====================== javax.ejb.SessionBean implementation =================*/


    public void ejbActivate() throws RemoteException {
    }


    public void ejbPassivate() throws RemoteException {
    }


    public void ejbRemove() throws RemoteException {
    }

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

    /*============== javax.ejb.SessionSynchronization implementation =============*/

 
    public void afterBegin() throws RemoteException {
        
    }

    public void beforeCompletion() throws RemoteException {
    }

    public void afterCompletion(boolean committed) throws RemoteException {

	}
	
	public Context getInitialContext() throws Exception {
	    if (initialContext == null){
	        Properties env = sessionContext.getEnvironment();
	        initialContext = new InitialContext(env);
	    }
        
	    return initialContext;
    }
    
    


     /*========================= Op implementation ============================*/

/****************** Database search ********************************************/

    
public HashMap getEmployeesForUnit(int bUnitRef) throws RemoteException{
	    //returns HashMap of name: oid
	    HashMap map = new HashMap();
	    try{
	        // get the current bUnits name IF its an employee
	        map = getEmployeeName(bUnitRef,map);
	        if (map.size()!=0)
	            return map;
	        else{
	            Vector v = findChildrenOf(bUnitRef);
	            map = getEmployees(v,map);
	        }
	    }catch(SQLException e){
	        throw new RemoteException(e.toString());
	    }
	    return map;
	}

    private HashMap getEmployees(Vector children,HashMap map) throws SQLException{
        // find all employees recursively
        for(int i=0;i<children.size();i++){
            Integer currentID = (Integer)children.elementAt(i);
            int id = currentID.intValue();
            map = getEmployeeName(id,map);
            map = getEmployees(findChildrenOf(id), map);
        }
        return map;
        
    }
   
    
    private Vector findChildrenOf(int bUnitRef) throws SQLException{
            //returns a Vector of oids that are the children of this oid
            Vector vec = new Vector();
	        PreparedStatement ps = con.prepareStatement("SELECT businessUnitOID FROM BusinessUnit where parent = ?");
	        ps.setInt(1, bUnitRef);
	        ResultSet result = ps.executeQuery();
	        while(result.next()){
	            int oid = result.getInt("businessUnitOID");
	            vec.addElement(new Integer(oid));
	        }
	        if(result != null) result.close();
	        if(ps != null) ps.close();
        return vec;
    }

    private HashMap getEmployeeName(int bUnitRef,HashMap map) throws SQLException{
        //adds the employee name and oid to map if unit found is an employee
	    PreparedStatement ps = null;
	    ResultSet result = null;
	    ps = con.prepareStatement("SELECT employeeRef,name FROM BusinessUnit where businessUnitOID = ?");
	        ps.setInt(1, bUnitRef);
	        result = ps.executeQuery();
	        while(result.next()){
	            int empRef = result.getInt("employeeRef");
	            String name = result.getString("name");
	            if(empRef!=0)
	                map.put(name,new Integer(bUnitRef));
	                
	        }
	     if(result != null) result.close();
	     if(ps != null) ps.close();
	  return map;
}
	        


/****************** Entity bean search ********************************************/

/* public ArrayList getEmployeesForUnit(int bUnitRef) throws RemoteException{
	   ArrayList employees = new ArrayList();
	   try{     
	        
            BusinessUnit bUnit = buHome.findByPrimaryKey(new PrimaryKey(bUnitRef));
            int empOID = bUnit.getEmployeeRef();
            if(empOID!=0){
                Employee emp = empHome.findByPrimaryKey(new PrimaryKey(empOID));
                employees.add(emp);
                return employees;
            }
            else
                employees = getEmployees(bUnit.getChildren(),employees);
       }catch(Exception e){
            throw new RemoteException(e.toString());}
       return employees;
    }
    
    public ArrayList getEmployees(ArrayList children, ArrayList employeeList)  throws RemoteException{
	   try{     
        
            BusinessUnit currentPass = null;
            for(int i=0;i<children.size();i++){
                currentPass = (BusinessUnit)children.get(i);
                int empOID = currentPass.getEmployeeRef();
                if(empOID!=0){
                    Employee emp = empHome.findByPrimaryKey(new PrimaryKey(empOID));
                    employeeList.add(emp);
                }
                employeeList = getEmployees(currentPass.getChildren(),employeeList);                
            }
        }catch(Exception e){
            throw new RemoteException(e.toString());}
        return employeeList;
    }
    
   */
}