package ibase.webitm.ejb.adm.adv;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.GenericUtility;

import ibase.system.config.ConnDriver;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.rmi.RemoteException;
import javax.ejb.Stateless; 

@Stateless 
public class EmpBondDefConfirm extends ActionHandlerEJB implements EmpBondDefConfirmLocal,EmpBondDefConfirmRemote 
{
	String loginEmpCode="";
	int updcnt1=0;
	public String confirm(String tranId, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		
		String retString = "";
		try
		{
			
			Connection conn=null;		
			retString = confirm( tranId, xtraParams, forcedFlag, conn);		
		
		}
		catch(Exception e)
		{
			System.out.println("Exception :EmpBondDefConfirm :confirm():" + e.getMessage() + ":");
			retString = GenericUtility.getInstance().createErrorString(e);
			e.printStackTrace();
		}
		return retString;
	}
	
	public String confirm( String tranId, String xtraParams, String forcedFlag, Connection conn)
	{
		System.out.println("--------------confirm method of EmpBondDefConfirm ------------- ");
		ResultSet rs = null;
		PreparedStatement pstmt = null;	
		 conn = null;
		 ITMDBAccessEJB itmdbAccess=new ITMDBAccessEJB();
		String retString = "",errString="";
		String sql = "",empcode="",confirmed="";
		double bondamt=0.0;
		int lineno=0,bondprd=0,updCnt=0;
		
		//Modified by Rahul Shenoy on 14/08/2015 [Declaration for inserting when value of line_no__ref is 0].Start
		String sqlInsert ="",sqlMaxLineNo ="";
		
		int maxLineNumber = 0,insertCnt = 0;
		PreparedStatement pstmtMax = null,pstmtInsert = null;
		ResultSet rsMax=null;
		//Modified by Rahul Shenoy on 14/08/2015 [Declaration for inserting when value of line_no__ref is 0].End
		
		
		try
		{		
			 loginEmpCode = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			conn.setAutoCommit(false);		
			
			sql = "SELECT CONFIRMED FROM EMPLOYEE_BOND_DEF WHERE TRAN_ID = ?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, tranId);
			rs = pstmt.executeQuery();
			if( rs.next() )
			{
				confirmed =rs.getString("CONFIRMED")==null ? "":rs.getString("CONFIRMED");
			}	
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
			if ( rs != null )
			{
				rs.close();
				rs = null;
			}
			if( confirmed != null && confirmed.equalsIgnoreCase("Y") )
			{
				errString = itmdbAccess.getErrorString("", "AEBCONF", "", "", conn);
				return errString;
			}
			
			// Modified by Piyush on 16/07/2015 [To establish join between header and detail]
				/*
				sql="select ed.tran_id,e.emp_code,ed.line_no,ed.bond_amt,ed.bond_prd from employee_bond_def_det ed,employee_bond_def e "+ 
							" where ed.tran_id=?";
				*/
				
			//Modified by RAHUL SHENOY on 14/08/2015 [Reference Line Number(line_no__ref) needs to be updated instead of Line Number from employee_bond_def_det table]
			/*
			sql="select ed.tran_id,e.emp_code,ed.line_no,ed.bond_amt,ed.bond_prd from employee_bond_def_det ed,employee_bond_def e "+ 
						" where e.tran_id = ed.tran_id and e.tran_id=?";
			*/
			ResultSet rs1 = null;
			PreparedStatement pstmt1 = null;
			
			
			
		
			/*
			 while(rs.next())
			{
				lineno=rs.getInt("line_no__ref");
				bondamt=rs.getDouble("bond_amt");
				bondprd=rs.getInt("bond_prd");
				empcode=rs.getString("emp_code");
				
				sql="update employee_bond set bond_amt = ?,bond_prd = ? where line_no = ? and emp_code = ?";
				pstmt = conn.prepareStatement(sql);
				
				pstmt.setDouble(1, bondamt); 
				pstmt.setInt(2, bondprd);
				pstmt.setInt(3, lineno);
				pstmt.setString(4,empcode);
				
				updCnt = pstmt.executeUpdate();
				pstmt.clearParameters();
			}*/
			
			sql="select ed.tran_id,e.emp_code,ed.line_no__ref,ed.bond_amt,ed.bond_prd from employee_bond_def_det ed,employee_bond_def e "+ 
					" where e.tran_id = ed.tran_id and e.tran_id=?";
			pstmt1 = conn.prepareStatement(sql);
			pstmt1.setString(1, tranId);
			rs1 = pstmt1.executeQuery();
			
			sql="update employee_bond set bond_amt = ?,bond_prd = ? where line_no = ? and emp_code = ?";
			pstmt = conn.prepareStatement(sql);
			
			sqlInsert = "Insert into employee_bond ( EMP_CODE , LINE_NO , BOND_PRD , BOND_AMT) values ( ? , ? , ? , ? )";
			pstmtInsert = conn.prepareStatement(sqlInsert);
			
			sqlMaxLineNo="select max(line_no) as max_line_no from employee_bond where emp_code = ? ";
			pstmtMax = conn.prepareStatement(sqlMaxLineNo);
			
			int totUpdCnt = 0;
			
			while(rs1.next())
			{
				System.out.println("*** Entering the ResultSet [rs] ***");
				
				lineno=rs1.getInt("line_no__ref");
				bondamt=rs1.getDouble("bond_amt");
				bondprd=rs1.getInt("bond_prd");
				empcode=rs1.getString("emp_code");
				
				//Modified by Rahul Shenoy on 14/08/2015 [Inserting where line_no__ref is 0 and updating when it is not 0 to the Employee_Bond table]
				if(lineno == 0)
				{
					System.out.println("*** Line Number is found to be 0 ***");
					//For Obtaining the available maximum line number for inserting into the master
					
					pstmtMax.setString(1, empcode);
					rsMax = pstmtMax.executeQuery();
					pstmtMax.clearParameters();
					
					while(rsMax.next())
					{
						maxLineNumber = rsMax.getInt("max_line_no");
					}
					
					
					if(maxLineNumber == 0)
					{
						System.out.println("*** No record present in the table for the given employee ***");
						System.out.println("Setting maxLine Number value as [1]");
						maxLineNumber = 1;
					}else
						{
							maxLineNumber = maxLineNumber + 1;
						}
					
					System.out.println("Available Max Line Number for inserting data :["+ maxLineNumber +"]");
					
					//For inserting the obtained values for 0 value of lineno 
					
					pstmtInsert.setString(1, empcode);
					pstmtInsert.setInt(2, maxLineNumber);
					pstmtInsert.setInt(3, bondprd);
					pstmtInsert.setDouble(4, bondamt);
					
					insertCnt = pstmtInsert.executeUpdate();
					totUpdCnt = totUpdCnt + insertCnt; 
					System.out.println("Value of insertCnt is : ["+insertCnt+"]");
					
				}else
				{//For updating values if line Number is not zero
					System.out.println("*** Line Number is found to be "+ lineno +" ***");
					
					
					pstmt.setDouble(1, bondamt); 
					pstmt.setInt(2, bondprd);
					pstmt.setInt(3, lineno);
					pstmt.setString(4,empcode);
					
					updCnt = pstmt.executeUpdate();
					totUpdCnt = totUpdCnt + updCnt; 
					
					System.out.println("Value of updCnt is : ["+updCnt+"]");
					pstmt.clearParameters();
				}
				//Modified by Rahul Shenoy on 14/08/2015 [Inserting where line_no__ref is 0 and updating when it is not 0 to the Employee_Bond table]
			}
			
			if ( rsMax != null )
			{
				rsMax.close();
				rsMax = null;
			}	
			
			if ( rs1 != null )
			{
				rs1.close();
				rs1 = null;
			}	
			
			if( pstmtInsert != null )
			{
				pstmtInsert.close();
				pstmtInsert = null;
			}
			
			if( pstmtMax != null )
			{
				pstmtMax.close();
				pstmtMax = null;
			}
			
			
			if( pstmt1 != null )
			{
				pstmt1.close();
				pstmt1 = null;
			}
			
			
			if( pstmt != null )
			{
				pstmt.close();
				pstmt = null;
			}
		
			
			//Added by RAHUL SHENOY on 21/08/2015 [Confirming the update].Start
			int count=0;
			String sqlConfirm = "UPDATE EMPLOYEE_BOND_DEF SET CONFIRMED = ? ,CONF_DATE = ?,EMP_CODE__APRV=? WHERE TRAN_ID = ?";
			
				pstmt1 = conn.prepareStatement( sqlConfirm );	
				pstmt1.setString(1, "Y");
				pstmt1.setTimestamp(2, this.getCurrdateAppFormat()); 
				pstmt1.setString(3, loginEmpCode);
				pstmt1.setString(4, tranId);
				
				updcnt1 = pstmt1.executeUpdate();
				System.out.println("confirm updated -------->>>>>>>>>updCount :"+count);
				
			//Added by RAHUL SHENOY on 21/08/2015 [Confirming the update].End
			
			
			
			//Modified by RAHUL SHENOY on 17/08/2015 [Displaying the Insert Count]
			//System.out.println("UPDATE COUNT --updCnt-->>"+updCnt+" updcnt1 -->>"+updcnt1);
			System.out.println("UPDATE COUNT --updCnt-->>"+updCnt+" insertCnt -->>"+ insertCnt+" updcnt1 -->>"+updcnt1);
			
			if (totUpdCnt > 0 && updcnt1 >0 )
			{			
				retString=new ITMDBAccessEJB().getErrorString("", "VCONFSUC", "", "", conn);
				conn.commit();
				System.out.println("Bond amount and bond period updated successfully.......");
				
			}else
			{
				
				retString=new ITMDBAccessEJB().getErrorString("", "VCONFUSUC", "", "", conn);
				conn.rollback();
				System.out.println("Not Updated Bond amount and bond period........");
			}
			
		}
		catch(Exception e)
		{
			try
			{
				conn.rollback();
			}
			catch (Exception e1)
			{
			}
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;					
				}	
				if (conn!=null)
				{
					conn.close();
					conn=null;
				}
							
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage());
				e.printStackTrace();
				
			}
		}
		System.out.println("Returning Result ::"+retString);
		return retString;
		
		
	}
	//Modified by RAHUL SHENOY on 21/08/2015 [Placing the update Confirm functionality inside the Action Handler method].Start
	/*
	 public int updateConfirm(Connection conn,String tranId)
	 
	{
		PreparedStatement pstmt1=null;
		int count=0;
		String sqlConfirm = "UPDATE EMPLOYEE_BOND_DEF SET CONFIRMED = ? ,CONF_DATE = ?,EMP_CODE__APRV=? WHERE TRAN_ID = ?";
		try
		{	
			pstmt1 = conn.prepareStatement( sqlConfirm );	
			pstmt1.setString(1, "Y");
			pstmt1.setTimestamp(2, this.getCurrdateAppFormat()); 
			pstmt1.setString(3, loginEmpCode);
			pstmt1.setString(4, tranId);
			
			count = pstmt1.executeUpdate();
			System.out.println("confirm updated -------->>>>>>>>>updCount :"+count);
			
			
		}
		catch(Exception e)
		{
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();					
		}
		try
		{
			if(pstmt1 != null)
			{
				pstmt1.close();
				pstmt1 = null;					
			}
				
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
			
		}
		return count;
	}
	
	*/ 
	//Modified by RAHUL SHENOY on 21/08/2015 [Placing the update Confirm functionality inside the Action Handler method].End
	 private java.sql.Timestamp getCurrdateAppFormat()
	    {
	        GenericUtility genericUtility = GenericUtility.getInstance();
			Timestamp timestamp = null;
	        try
	        {
	            java.util.Date date = null;
	            timestamp = new Timestamp(System.currentTimeMillis());            
	            SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
	            date = simpledateformat.parse(timestamp.toString());
	            timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
	        }
	        catch(Exception exception)
	        {
	            System.out.println("Exception in [EmpBondDefConfirm] getCurrdateAppFormat " + exception.getMessage());
	        }
	        return timestamp;
	    }
	
}
	
	