package ibase.webitm.ejb.fin;
import ibase.webitm.utility.*;
import ibase.webitm.ejb.*;
import ibase.system.config.*;

import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.ejb.Stateless; // added for ejb3
@Stateless // added for ejb3

public class  SundrybalOpenConf  extends ActionHandlerEJB implements SundrybalOpenConfLocal,SundrybalOpenConfRemote //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 resultStr = "";
		try
		{
			System.out.println("Confirming Sundrybal Opening.......");
			resultStr =  confirmSundrybalOpen(tranID,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception [01][confirm]::"+e.getMessage());
			e.printStackTrace();
			System.out.println("Exception ::"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("Returning Result ::"+resultStr);
		return resultStr;
	}

	private	String confirmSundrybalOpen(String tranID,String xtraParams)throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null, stmt1 = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		ResultSet rsHdr = null;
		ResultSet rsDtl = null;
		ResultSet rsMast = null;
		ResultSet rs = null;
		String empCode = "", userId = "";
		String sqlHdr = "", sqlIns = "", sqlDtl = "", sqlCnt = "", sqlUpd = "";
		String sql = "", errCode = "";
		String retString = "", contactCode = "", column = "", table = "";
		String siteCode = "", finEntity = "", currCode = "", prdCode = "", acctPrd = "", chgUser = "", chgTerm = "";
		String confirmed = "", acctCode = "", cctrCode = "", updSql = "", sundryType = "", sundryCode = "";
		double exchRate = 0d, crAmt = 0d, drAmt = 0d, crAmtBase = 0d, drAmtBase = 0d;
		double crAmtOld = 0d, drAmtOld = 0d, crAmtBaseOld = 0d, drAmtBaseOld = 0d, advAmount = 0d;
		int upd = 0, acctbalCnt = 0, sundrybalCnt = 0, count = 0;

		java.sql.Timestamp chgDate = null, tranDate = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
		userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		HashMap sundrybalMap = new HashMap();
		HashMap acctbalMap = new HashMap();
		
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false); 
		}
		catch(Exception e)
		{
			System.out.println("[Exception In Connection Established:][confirmSundrybalOpen]:: "+e);
			e.printStackTrace();
			retString = e.getMessage();
			return retString; 
		}
		try
		{
			sqlHdr = "SELECT SITE_CODE, FIN_ENTITY, CURR_CODE, ACCT_PRD, PRD_CODE, TRAN_DATE, " +
					" (CASE WHEN CONFIRMED IS NULL THEN 'N' ELSE CONFIRMED END) AS CONFIRMED, " +
					" CHG_DATE, CHG_USER, CHG_TERM  FROM SUNDRYBAL_HDR WHERE TRAN_ID ='"+tranID.trim()+"'";	
			System.out.println("sqlHdr :: " + sqlHdr);
			stmt = conn.createStatement();
			rsHdr = stmt.executeQuery(sqlHdr);
			if (rsHdr.next())
			{
				siteCode	= rsHdr.getString("SITE_CODE");
				finEntity	= rsHdr.getString("FIN_ENTITY");
				currCode	= rsHdr.getString("CURR_CODE"); 
				tranDate	= rsHdr.getTimestamp("TRAN_DATE"); 
				prdCode		= rsHdr.getString("PRD_CODE");
				acctPrd		= rsHdr.getString("ACCT_PRD");
				confirmed	= rsHdr.getString("CONFIRMED");
				chgDate		= rsHdr.getTimestamp("CHG_DATE");
				chgUser		= rsHdr.getString("CHG_USER"); 
				chgTerm		= rsHdr.getString("CHG_TERM");
			}
			System.out.println("siteCode :: " + siteCode);
			System.out.println("finEntity :: " + finEntity);
			System.out.println("currCode :: " + currCode);
			System.out.println("tranDate :: " + tranDate);
			System.out.println("prdCode :: " + prdCode);
			System.out.println("acctPrd :: " + acctPrd);
			System.out.println("confirmed :: " + confirmed);
			System.out.println("chgDate :: " + chgDate);
			System.out.println("chgUser :: " + chgUser);
			System.out.println("chgTerm :: " + chgTerm);
		}
		catch(SQLException se)
		{
			System.out.println("SQLException [02][SundrybalOpenConfEJB][confirmSundrybalOpen()][Excuting Query Failed]:: " + sql + se.getMessage());
			se.printStackTrace();
			retString = se.getMessage();
			return retString;
		}
		catch(Exception e)
		{
			System.out.println("Exception [03][SundrybalOpenConfEJB][confirmSundrybalOpen()][Excuting Query Failed]:: " + sql + e.getMessage());
			e.printStackTrace();
			retString = e.getMessage();
			return retString;
		}
		finally
		{
			try
			{
				rsHdr.close();
				rsHdr = null;
				stmt.close();
				stmt = null;
			}
			catch(Exception e)
			{
				System.out.println("Exception [04][SundrybalOpenConfEJB][confirmSundrybalOpen()]:: " + e.getMessage());
				e.printStackTrace();
				retString = e.getMessage();
				System.out.println("Exception In Closing Statement and ResultSet" + retString);
				return retString; 
			}
		}
		if(confirmed.trim().equalsIgnoreCase("Y"))
		{
			retString =	itmDBAccessEJB.getErrorString("","VTMCONF1","","",conn);
		}
		else
		{
			try
			{
				sqlDtl = "SELECT SUNDRY_TYPE, SUNDRY_CODE, 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 SUNDRYBAL_DET WHERE TRAN_ID ='"+tranID.trim()+"'";	 
				stmt = conn.createStatement();
				rsDtl = stmt.executeQuery(sqlDtl);
				while (rsDtl.next())
				{
					sundryType	 = rsDtl.getString("SUNDRY_TYPE");
					sundryCode	 = rsDtl.getString("SUNDRY_CODE");
					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");
					try
					{
						stmt1 = conn.createStatement();
						if(sundryType.equals("B"))
						{
							contactCode = " ";
						}
						else if(sundryType.equals("E"))
						{
							table = "EMPLOYEE";
							column = "EMP_CODE";
							sql = "SELECT CONTACT_CODE FROM EMPLOYEE WHERE EMP_CODE = '"+sundryCode.trim()+"'";
							System.out.println("sql ::: " + sql);
							rs = stmt1.executeQuery(sql);
							if(rs.next())
							{
								contactCode = rs.getString("CONTACT_CODE");
							}
							if (contactCode == null)
							{
								contactCode = " ";
							}
						}
						else if(sundryType.equals("P"))
						{
							table = "SALES_PERS";
							column = "SALES_PERS";
							sql = "SELECT CONTACT_CODE FROM SALES_PERS WHERE SALES_PERS = '"+sundryCode.trim()+"'";
							System.out.println("sql ::: " + sql);
							rs = stmt1.executeQuery(sql);
							if(rs.next())
							{
								contactCode = rs.getString("CONTACT_CODE");
							}
							if (contactCode == null)
							{
								contactCode = " ";
							}
						}
						else if (sundryType.equals("L"))
						{//added by nisar on 17/01/08
							sql = "SELECT CONTACT_CODE FROM LOANPARTY WHERE PARTY_CODE = '"+sundryCode.trim()+"'";
							System.out.println("sql ::: " + sql);
							rs = stmt1.executeQuery(sql);
							if(rs.next())
							{
								contactCode = rs.getString("CONTACT_CODE");
							}
							if (contactCode == null)
							{
								contactCode = " ";
							}
						}
						else if (sundryType.equals("T"))
						{//added by nisar on 17/01/08
							sql = "SELECT CONTACT_CODE FROM TRANSPORTER WHERE TRAN_CODE = '"+sundryCode.trim()+"'";
							System.out.println("sql ::: " + sql);
							rs = stmt1.executeQuery(sql);
							if(rs.next())
							{
								contactCode = rs.getString("CONTACT_CODE");
							}
							if (contactCode == null)
							{
								contactCode = " ";
							}
						}
					}
					catch(SQLException se)
					{
						System.out.println("SQLException [05]:[SundrybalOpenConfEJB][confirmSundrybalOpen()][Excuting Query Failed]:: " +sql+ se.getMessage());
						se.printStackTrace();
						retString = se.getMessage();
						System.out.println("retString :: " + retString);
						return retString; 
					}
					finally
					{
						try
						{
							System.out.println("Closing ResultSet and Statement.......");
							if (rs != null)
							{
								rs.close();
								rs = null;
							}
							if (stmt1 != null)
							{
								stmt1.close();
								stmt1 = null;
							}
						}
						catch(Exception e){}
					}
					System.out.println("crAmt :: " + crAmt);
					System.out.println("drAmt :: " + drAmt);
					System.out.println("crAmtOld :: " + crAmtOld);
					System.out.println("drAmtOld :: " + drAmtOld);

					//Added Changes  Gulzar - 16/07/08 - Req ID:FI89PHE007
					sql = "SELECT CR_AMT, DR_AMT  FROM SUNDRYBAL "+
						  "WHERE ACCT_PRD = '"+acctPrd+"' AND PRD_CODE = '"+prdCode+"' AND FIN_ENTITY = '"+finEntity+"' "+
						  "AND SITE_CODE = '"+ siteCode +"' AND ACCT_CODE = '"+acctCode+"' AND CCTR_CODE = '"+cctrCode+"' " +
						  "AND SUNDRY_TYPE = '"+sundryType+"' AND SUNDRY_CODE = '"+sundryCode+"'";
					System.out.println("sql ::"+ sql);
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sql);
					if ( rs.next())
					{
						crAmtOld = rs.getDouble("CR_AMT");
						drAmtOld = rs.getDouble("DR_AMT");
					}
					else
					{
						crAmtOld = 0d;
						drAmtOld = 0d;
					}
					//End Changes - Gulzar - 16/07/08 - Req ID:FI89PHE007
					
					crAmt = crAmt - crAmtOld;
					drAmt = drAmt - drAmtOld;

					sundrybalMap.put("tran_date",tranDate);
					sundrybalMap.put("fin_entity",finEntity.trim());
					sundrybalMap.put("site_code",siteCode.trim());
					sundrybalMap.put("sundry_type",sundryType.trim());
					sundrybalMap.put("sundry_code",sundryCode.trim());
					sundrybalMap.put("acct_code",acctCode.trim());
					sundrybalMap.put("cctr_code",cctrCode.trim());
					sundrybalMap.put("curr_code",currCode.trim());
					sundrybalMap.put("acct_prd",acctPrd.trim()); 
					sundrybalMap.put("contact_code",contactCode.trim());
					sundrybalMap.put("user_id",userId.trim());
					sundrybalMap.put("exch_rate",new Double(exchRate));
					sundrybalMap.put("dr_amt",new Double(drAmt));
					sundrybalMap.put("cr_amt",new Double(crAmt));
					sundrybalMap.put("adv_amt",new Double(advAmount));
					
					System.out.println("sundrybalMap In SundrybalOpenConfEJB :: " + sundrybalMap);

					FinCommon finCommon = new FinCommon();
					errCode = finCommon.sundrybalOpnUpd(sundrybalMap,conn);
					sundrybalMap.clear();
					System.out.println("Error Code........"+errCode);
					if(errCode.trim().length()>0)
					{
						retString = itmDBAccessEJB.getErrorString("", "errCode", userId);
						break;
					}
					System.out.println("RETURN FROM SUNDRYBAL ENTRIES");

					//Inserting into ACCTBAL...........
					System.out.println("Inserting into ACCTBAL......");
					acctbalMap.put("contact_code",contactCode);
					acctbalMap.put("tran_date",tranDate);
					acctbalMap.put("eff_date",tranDate);
					acctbalMap.put("fin_entity",finEntity.trim());
					acctbalMap.put("site_code",siteCode.trim());
					acctbalMap.put("acct_code",acctCode.trim());
					acctbalMap.put("cctr_code",cctrCode);
					acctbalMap.put("curr_code",currCode.trim());
					acctbalMap.put("emp_code",empCode.trim());
					acctbalMap.put("user_id",userId.trim());
					acctbalMap.put("exch_rate",new Double(exchRate));
					acctbalMap.put("dr_amt",new Double(drAmt));
					acctbalMap.put("cr_amt",new Double(crAmt));
					acctbalMap.put("acct_prd",acctPrd.trim()); 

					System.out.println("acctbalMap In SundrybalOpenConfEJB :: " + acctbalMap);

					errCode = finCommon.acctbalOpnUpd(acctbalMap,conn);
					acctbalMap.clear(); 
					if(errCode.trim().length()>0)
					{
						break;
					}
					System.out.println("RETURN FROM ACCTBAL ENTRIES");

				}//While Loop
				try
				{
					updSql = "UPDATE SUNDRYBAL_HDR SET CONFIRMED = 'Y', CONF_DATE = ?  ,EMP_CODE__APRV = ? where TRAN_ID = ?";
					System.out.println("Update SUNDRYBAL_HDR ::"+ updSql);
					pstmt = conn.prepareStatement(updSql);
					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("SUNDRYBAL_HDR Updated...(Confirmed)" + userId);
						conn.commit();						
						retString = itmDBAccessEJB.getErrorString("","VTMCONF2",userId);
						System.out.println("Ret String: " + retString);
					}
				}
				catch(SQLException se)
				{
					System.out.println("SQLException[06] :[SundrybalOpenConfEJB][confirmSundrybalOpen()][Update Query Failed]:: " + se.getMessage());
					se.printStackTrace();
					conn.rollback();
					retString = se.getMessage();
					return retString;
				}
				catch(Exception e)
				{
					retString = "Not Confirmed";
					conn.rollback();
					System.out.println("Exception[07] ::"+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 [08]: Connection Error Closed :" + se.getMessage());
						se.printStackTrace();
						retString = "Connection Not Closed :" + se.getMessage();
						return retString;
					}
				}//finally
			}//End Try Block
			catch(Exception e)
			{
				System.out.println("Exception [09]:[SundrybalOpenConfEJB][confirmSundrybalOpen]:" + e.getMessage());
				e.printStackTrace();
				try
				{
					conn.rollback(); 
				}
				catch(Exception e1){}
				retString = e.getMessage();
				return retString;
			}
			finally
			{
				try
				{
					System.out.println("Closing Connection In Finally Block...............");
					if (rsDtl != null)
					{
						rsDtl.close();
						rsDtl = null;
					}
					if (stmt != null)
					{
						stmt.close();
						stmt = null;
					}
					if (conn != null)
					{
						conn.close();
						conn = null;
					}
				}
				catch(Exception e)
				{
					System.out.println("Exception [10]:[SundrybalOpenConfEJB][confirmSundrybalOpen()]" + e.getMessage());
					e.printStackTrace();
					retString = e.getMessage();
					return retString;
				}
			}// Finally Block
		}//End Else Block
		System.out.println("retString ::"+retString);
		return retString;
	}
}