package ibase.webitm.ejb.fin;

import java.rmi.RemoteException;
import java.sql.*;
import javax.ejb.*;

import ibase.webitm.utility.*;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class GlOpenConf  extends ActionHandlerEJB implements GlOpenConfLocal,GlOpenConfRemote //SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Entering the ejb of confirmation................");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/

	public String confirm(String tranID,String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		String result = "";
		try
		{
			System.out.println("Confirming Glopenig....");
			result =  confirmGlOpenConf(tranID,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("Returning Result ::"+result);
		return result;
	}
	private	String confirmGlOpenConf(String tranID,String xtraParams)throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		Statement lstmt = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		ResultSet rsHdr = null;
		ResultSet rsDtl = null;
		ResultSet rsMast = null;
		ResultSet rs = null;
		String sqlHdr = "";
		String sqlIns = "";
		String sqlDtl = "";
		String sql = "";
		String retString = "";
		String userId = "";
		String tranType= "";
		String siteCode = "";
		String finEnt = "";
		String currCode = "";
		String acctCode = "";
		String acctPrd = "";
		String cctrCode = "";
		String prdCode = "";
		String sqlUpd = "";
		double cr_o = 0.0;
		double dr_o = 0.0;
		double crAmt = 0.0;
		double exchRate = 0.0;
		double drAmt = 0.0;
		double crAmtBase = 0.0;
		double drAmtBase = 0.0;
		double crAmtOld = 0.0;
		double drAmtOld = 0.0;
		double crAmtBaseOld = 0.0;
		double drAmtBaseOld= 0.0;
		String empCodeApprv = "";
		java.util.Date chgDate = null;
		String chgUser = "";
		String chgTerm = "";
		String update = "";
		int upd = 0;
		int cnt = 0;
		double cr_z =0.0;
		double dr_z =0.0;

		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		String empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
		userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false); //Gulzar 06-12-06
		}
		catch(Exception ex)
		{
			System.out.println("[Exception In Connection Established:]"+ex);
			ex.printStackTrace();
			retString = ex.getMessage();
			return retString;
		}	
			
 //		SELECT DATA FROM GL_HDR 
		try
		{
			sql = "SELECT SITE_CODE, FIN_ENTITY, CURR_CODE, ACCT_PRD, PRD_CODE, CHG_DATE, CHG_USER, CHG_TERM  FROM GL_HDR WHERE TRAN_ID ='"+tranID.trim()+"'";	 
			stmt = conn.createStatement();
			rsHdr = stmt.executeQuery(sql);
			if (rsHdr.next())
			{
				siteCode	= rsHdr.getString("SITE_CODE");
				finEnt		= rsHdr.getString("FIN_ENTITY");
				currCode	= rsHdr.getString("CURR_CODE"); 
				prdCode		= rsHdr.getString("PRD_CODE");
				acctPrd		= rsHdr.getString("ACCT_PRD");
				chgDate		= rsHdr.getDate("CHG_DATE");
				chgUser		= rsHdr.getString("CHG_USER");
				chgTerm		= rsHdr.getString("CHG_TERM");
			}
		}
		catch(SQLException se)
		{
			System.out.println("SQLException [04][GlOpenConf][Excuting Query Failed]" + sql + se.getMessage());
			se.printStackTrace();
			retString = se.getMessage();
			return retString;
		}
		catch(Exception e)
		{
			System.out.println("Exception [05][GlOpenConf][Excuting Query Failed]" + sql + e.getMessage());
			e.printStackTrace();
			retString = e.getMessage();
			return retString;
		}
		finally
		{
			try
			{
				stmt.close();
				stmt = null;
				rsHdr.close();
				rsHdr = null;
			}
			catch(Exception e)
			{
				System.out.println("Exception [06][GlOpenConf]" + e.getMessage());
				e.printStackTrace();
				retString = e.getMessage();
				System.out.println("Exception In Closing Statement and ResultSet" + retString);
				return retString; 
			}
		}
//		TESTING FOR CONFIRM FIELD
		if(dupConf( tranID, conn))
		{
			System.out.println("Transaction Is Already Confirmed For : " + tranID);
			retString =	itmDBAccessEJB.getErrorString("","VTRCONF1","","",conn);
		}
		else
		{
//			TRAVERSING EACH RECORD FROM GL_DTL FOR A PARTICULAR TRAN ID
			try
			{
				sqlDtl = "SELECT ACCT_CODE,CCTR_CODE ,EXCH_RATE ,CR_AMT ,DR_AMT ,CR_AMT__BASE,DR_AMT__BASE,CR_AMT__OLD,DR_AMT__OLD,CR_AMT__BASE__OLD,DR_AMT__BASE__OLD from gl_dtl WHERE TRAN_ID ='"+tranID+"'";	 
				lstmt = conn.createStatement();
				rsDtl = lstmt.executeQuery(sqlDtl);
				while (rsDtl.next())
				{	
					acctCode	= rsDtl.getString("ACCT_CODE");
					cctrCode	= rsDtl.getString("CCTR_CODE");
					exchRate	= rsDtl.getDouble("EXCH_RATE");
					crAmt		= rsDtl.getDouble("CR_AMT");
					drAmt		= rsDtl.getDouble("DR_AMT");
					crAmtBase	= rsDtl.getDouble("CR_AMT__BASE");
					drAmtBase	= rsDtl.getDouble("DR_AMT__BASE");
					crAmtOld	= rsDtl.getDouble("CR_AMT__OLD");
					drAmtOld	= rsDtl.getDouble("DR_AMT__OLD");
					crAmtBaseOld = rsDtl.getDouble("CR_AMT__BASE__OLD");
					drAmtBaseOld= rsDtl.getDouble("DR_AMT__BASE__OLD");
										
//					TESTING WHEATHER ZZZZZZ PRDCODE ALREADY THEIR IN ACCTBAL
					try
					{
						sql = "SELECT COUNT(*) AS COUNT  FROM ACCTBAL "+
						"WHERE ACCT_PRD = '"+acctPrd+"' AND PRD_CODE = '000000' AND FIN_ENTITY = '"+finEnt+"' AND SITE_CODE = '"+siteCode+"' "+
						"AND ACCT_CODE = '"+acctCode+"' AND CCTR_CODE = '"+cctrCode+"' ";
						
						stmt = conn.createStatement();
						rsMast = stmt.executeQuery(sql);  
						
						if (rsMast.next())
						{
							cnt = rsMast.getInt("COUNT");
						}
						System.out.println(  "COUNT::::::"+cnt);
					}
					catch(SQLException se)
					{
						System.out.println("SQLException [04][GlOpenConf][Excuting Query Failed]" + sql + se.getMessage());
						se.printStackTrace();
						retString = se.getMessage();
						return retString;
					}
					catch(Exception e)
					{
						System.out.println("Exception [05][GlOpenConf][Excuting Query Failed]" + sql + e.getMessage());
						e.printStackTrace();
						retString = e.getMessage();
						return retString;
					}
					finally
					{
						try
						{
							stmt.close();
							stmt = null;
							rsMast.close();
							rsMast = null;
						}
						catch(Exception e)
						{
							System.out.println("Exception [06][GlOpenConf]" + e.getMessage());
							e.printStackTrace();
							retString = e.getMessage();
							System.out.println("Exception In Closing Statement and ResultSet" + retString);
							return retString; 
						}
					}
					if (cnt == 0)
					{
						try
						{
							System.out.println("NO RECORD FOR ZZZZZZ IN MASTER INSERTING A NEW RECORD FOR 000000");
							sqlIns = "INSERT INTO ACCTBAL (ACCT_PRD, PRD_CODE, FIN_ENTITY, SITE_CODE,"+ 
							"ACCT_CODE, CCTR_CODE, DR_AMT, CR_AMT, CURR_CODE__AC,"+ 
							"DR_AMT__BASE, CR_AMT__BASE, CHG_DATE, CHG_USER, CHG_TERM)"+
							"VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,? )";
							System.out.println("Inserting Into ACCTBAL FOR 000000 :: "+sqlIns);
							pstmt = conn.prepareStatement(sqlIns);
							pstmt.setString(1,acctPrd);
							pstmt.setString(2,"000000");
							pstmt.setString(3,finEnt);
							pstmt.setString(4,siteCode);
							pstmt.setString(5,acctCode);
							pstmt.setString(6,cctrCode);
							pstmt.setDouble(7,drAmt);
							pstmt.setDouble(8,crAmt);
							pstmt.setString(9,currCode);
							pstmt.setDouble(10,drAmtBase);
							pstmt.setDouble(11,crAmtBase);
							pstmt.setTimestamp(12,new java.sql.Timestamp(System.currentTimeMillis()));
							pstmt.setString(13,chgUser);
							pstmt.setString(14,chgTerm);
							pstmt.executeUpdate();
							System.out.println("Query Executed ::INSERT A RECORD FOR 000000 IN MASTER");
						}
						catch(SQLException se)
						{
							System.out.println("SQLException [10][GlOpenConf][Insert Query Failed]" + sqlIns + se.getMessage());
							try
							{
								conn.rollback();	
							}
							catch(Exception e)
							{
								System.out.println("Exception In Rollback Transaction");
							}
							se.printStackTrace();
							retString = se.getMessage();
							return retString;
						}
						catch(Exception e)
						{
							System.out.println("Exception [11][GlOpenConf][Insert Query Failed]" + sqlIns + e.getMessage());
							e.printStackTrace();
							retString = e.getMessage();
							return retString;
						}
						finally
						{
							try
							{
								pstmt.close();
								pstmt = null;
							}
							catch(Exception e)
							{
								System.out.println("Exception [12][GlOpenConf]" + sqlIns + e.getMessage());
								e.printStackTrace();
								retString = e.getMessage();	
								return retString;
							}
						}
				
//						INSERT A  RECORD FOR ZZZZZZ IN ACCTBAL 
						try
						{
							System.out.println("NO RECORD FOR ZZZZZZ IN MASTER INSERTING A NEW RECORD FOR ZZZZZZ");
							sqlIns = "INSERT INTO ACCTBAL (ACCT_PRD, PRD_CODE, FIN_ENTITY, SITE_CODE,"+ 
									"ACCT_CODE, CCTR_CODE, DR_AMT, CR_AMT, CURR_CODE__AC,"+ 
									"DR_AMT__BASE, CR_AMT__BASE, CHG_DATE, CHG_USER, CHG_TERM)"+
									"VALUES ( ?,?,?,?,?,?,?,?,?,?,?,?,?,? )";
							System.out.println("Inserting Into ACCTBAL FOR zzzzzz :: "+sqlIns);
					
							pstmt = conn.prepareStatement(sqlIns);
							pstmt.setString(1,acctPrd);
							pstmt.setString(2,"zzzzzz");
							pstmt.setString(3,finEnt);
							pstmt.setString(4,siteCode);
							pstmt.setString(5,acctCode);
							pstmt.setString(6,cctrCode);
							pstmt.setDouble(7,drAmt);
							pstmt.setDouble(8,crAmt);
							pstmt.setString(9,currCode);
							pstmt.setDouble(10,drAmtBase);
							pstmt.setDouble(11,crAmtBase);
							pstmt.setTimestamp(12,new java.sql.Timestamp(System.currentTimeMillis()));
							pstmt.setString(13,chgUser);
							pstmt.setString(14,chgTerm);
							pstmt.executeUpdate();
							System.out.println("Query Executed ::INSERT A RECORD FOR ZZZZZZ IN MASTER");
						}
						catch(SQLException se)
						{
							System.out.println("SQLException [10][GlOpenConf][Insert Query Failed]" + sqlIns + se.getMessage());
							try
							{
								conn.rollback();	
							}
							catch(Exception e)
							{
								System.out.println("Exception In Rollback Transaction");
							}
							se.printStackTrace();
							retString = se.getMessage();
							return retString;
						}
						catch(Exception e)
						{
							System.out.println("Exception [11][GlOpenConf][Insert Query Failed]" + sqlIns + e.getMessage());
							e.printStackTrace();
							retString = e.getMessage();
							return retString;
						}
						finally
						{
							try
							{
								pstmt.close();
								pstmt = null;
							}
							catch(Exception e)
							{
								System.out.println("Exception [12][GlOpenConf]" + sqlIns + e.getMessage());
								e.printStackTrace();
								retString = e.getMessage();	
								return retString;
							}
						}
					}	
//					RECORD FOUND IN ACCTBAL
					else
					{
						System.out.println("RECORD FOR 000000 FOUND IN MASTER UPDATE IS IN PROGRESS...........");
					
						try
						{
							System.out.println("UPDATE RECORD FOR 000000 and zzzzzz IN MASTER ...............");
							System.out.println("crAmt"+crAmt);
							System.out.println("crAmtOld"+crAmtOld);
							System.out.println("drAmt"+drAmt);
							System.out.println("drAmtOld"+drAmtOld);
							
							crAmt = crAmt - crAmtOld ;
							drAmt = drAmt - drAmtOld;
							crAmtBase = crAmtBase - crAmtBaseOld;
							drAmtBase =  drAmtBase - drAmtBaseOld;
							System.out.println("crAmt = crAmt - crAmtOld"+crAmt);
							System.out.println("drAmt = drAmt - drAmtOld"+drAmt);
							System.out.println("crAmtBase = crAmtBase - crAmtBaseOld"+crAmtBase);
							System.out.println("drAmtBase =  drAmtBase - drAmtBaseOld"+drAmtBase);
							/*-- Commented and Changes below Gulzar 
							sqlUpd = "UPDATE ACCTBAL SET DR_AMT = DR_AMT + "+drAmt+", CR_AMT = CR_AMT + "+crAmt+
							" ,DR_AMT__BASE = DR_AMT__BASE + "+drAmtBase+", CR_AMT__BASE = CR_AMT__BASE + "+crAmtBase+
							" WHERE ACCT_PRD = '"+acctPrd+"' AND FIN_ENTITY ='"+finEnt+"'"+ 
							" AND SITE_CODE ='"+siteCode+"' AND ACCT_CODE = '"+acctCode+"' AND	CCTR_CODE ='"+cctrCode+"' AND  PRD_CODE IN ( '000000','zzzzzz')";*/
					
							sqlUpd = "UPDATE ACCTBAL SET DR_AMT = DR_AMT + ( ? ), CR_AMT = CR_AMT + ( ? ), " +
							" DR_AMT__BASE = DR_AMT__BASE + ( ? ), CR_AMT__BASE = CR_AMT__BASE + ( ? ), " +
							" CHG_DATE = ?, CHG_USER = ?, CHG_TERM = ? " +
							" WHERE ACCT_PRD = '"+acctPrd+"' AND FIN_ENTITY ='"+finEnt+"'"+ 
							" AND SITE_CODE ='"+siteCode+"' AND ACCT_CODE = '"+acctCode+"' AND	CCTR_CODE ='"+cctrCode+"' AND  PRD_CODE IN ( '000000','zzzzzz')";	

							pstmt = conn.prepareStatement(sqlUpd);
						
							pstmt.setDouble(1,drAmt);
							pstmt.setDouble(2,crAmt);
							pstmt.setDouble(3,drAmtBase);
							pstmt.setDouble(4,crAmtBase);
							pstmt.setTimestamp(5,new java.sql.Timestamp(System.currentTimeMillis()));
							pstmt.setString(6,userId.trim());
							pstmt.setString(7,userId.trim());
							int u = pstmt.executeUpdate();
							if (u < 1)
							{
								System.out.println("Update Into ACCTBAL Failed : " + sqlUpd );
							}
							System.out.println("Update Into ACCTBAL sucessfully");
						}
						catch(SQLException se) //Gulzar
						{
							System.out.println("SQLException [10][GlOpenConf][Update Query Failed]" + sqlUpd + se.getMessage());
							try
							{
								conn.rollback();	
							}
							catch(Exception e)
							{
								System.out.println("Exception In Rollback Transaction");
							}
							se.printStackTrace();
							retString = se.getMessage();
							return retString;
						}
						catch(Exception e) //Gulzar
						{
							System.out.println("Exception [11][GlOpenConf][Update Query Failed]" + sqlUpd + e.getMessage());
							e.printStackTrace();
							retString = e.getMessage();
							return retString;
						}
						finally
						{
							try
							{
								pstmt.close();
								pstmt = null;
							}
							catch(Exception e)
							{
								System.out.println("Exception [12][GlOpenConf]" + sqlUpd + e.getMessage());
								e.printStackTrace();
								retString = e.getMessage();	
								return retString;
							}
						}//Finally Block
					}//Else Block
				}//While Loop
		//		UPDATE THE GL_HDR CONFIRMED FIELD
				try
				{
					System.out.println("emp code:="+empCode);
					update = "UPDATE GL_HDR SET CONFIRMED = 'Y', CONF_DATE = ?  ,EMP_CODE__APRV = ? where TRAN_ID = ?";
					System.out.println("Update Sorder ::"+ update);
					pstmt = conn.prepareStatement(update);
					pstmt.setTimestamp(1,new java.sql.Timestamp(System.currentTimeMillis()));
					pstmt.setString(2,empCode);
					pstmt.setString(3,tranID);
					upd = pstmt.executeUpdate();
					if (upd == 1)
					{
						System.out.println("GL_HDR Updated...(Confirmed)" + userId);
						conn.commit();						
						retString = itmDBAccessEJB.getErrorString("","VTMCONF2",userId);
						System.out.println("Ret String: " + retString);
					}
					else
					{
						System.out.println("GL_HDR Not Updated...(Not Confirmed)");
					}
				}
				catch(SQLException se) //Gulzar
				{
					System.out.println("SQLException[16] :[GlOpenConfEJB][Update Query Failed]" + update + se.getMessage());
					se.printStackTrace();
					conn.rollback();
					retString = se.getMessage();
					return retString;
				}
				catch(Exception e)
				{
					retString = "Not Confirmed";
					conn.rollback();
					System.out.println("Exception[17] ::"+e.getMessage());
					e.printStackTrace();
					retString = "Not Confirmed :" + e.getMessage();
				}
				finally
				{
					try
					{
						if(pstmt != null)
						{
							pstmt.close();
							pstmt = null;
						}
					}
					catch(SQLException se)
					{
						System.out.println("SQLException [18] Connection Error Closed :" + se.getMessage());
						se.printStackTrace();
						retString = "Connection Not Closed :" + se.getMessage();
						return retString;
					}
				}//finally
			}//Try Block
			catch(Exception e)
			{
				System.out.println("Exception [19][confirmGlOpenConf]:" + e.getMessage());
				e.printStackTrace();
				try
				{
					conn.rollback(); //Added by Jiten 27/07/06
				}
				catch(Exception e1){}
				retString = e.getMessage();
				return retString;
			}
			finally //Gulzar
			{
				try
				{
					if (rsDtl != null)
					{
						rsDtl.close();
						rsDtl = null;
					}
					if (lstmt != null)
					{
						lstmt.close();
						lstmt = null;
					}
					if (conn != null)
					{
						conn.close();
						conn = null;
					}
				}
				catch(Exception e)
				{
					System.out.println("Exception [20][confirmGlOpenConf]" + e.getMessage());
					e.printStackTrace();
					retString = e.getMessage();
					return retString;
				}
			}// Finally Block
		}//Else Block				
		System.out.println("retString ::"+retString);
		return retString;
	}
	private boolean dupConf(String tarnID,Connection conn) throws ITMException
	{
		Statement stmt = null;
		ResultSet rs = null;
		String sql="";
		boolean flag = false; 
		try
		{
			sql = " SELECT COUNT(*) FROM GL_HDR" +
						" WHERE TRAN_ID = '"+ tarnID +"' AND CONFIRMED = 'Y' ";
						
			System.out.println("[ConfirmGl_openEJB:] [dupConf] EXECUTE SELECT: "+sql);
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if(rs.next())
			{
				if(rs.getInt(1)!= 0)
				{
					flag = true;
				}
			}
			rs.close();
			stmt.close();
		}
		catch(SQLException e)
		{
			System.out.println("Exception : ConfirmGl_openEJB [dupConf]:==>\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return flag;
	}
}