//Win Name = W_BANK_RECO_MULTISEL

//Modification:
//05062007 	- 1)The display sequence changes (Changes on Datawindow)(Tarani)
//			-2)Currence code to be consider from bank statement and banktran log(Tarani)
//			-3)partial reconcilation no to be done(Tarani)
//14062007 - 1)if two record present in banktransaction and one record select from banktranlog then one record
// 				is reconcile and other is pending(Tarani)
//			2)It is not allowed to select multiple record from bankstatement and banktran log(Tarani)
//			3)amount calculation from payment & receipt (Tarani)

//Modification by msalam on18/06/07
//1. Allow multiple to multiple processing.
//2. Dont allow Tran-type P & R processing at a time in case of multiple to multiple operation.
 
package ibase.webitm.ejb.fin;

import java.util.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class  BankReconcileMultiSelPrc extends ibase.webitm.ejb.ProcessEJB implements BankReconcileMultiSelPrcLocal,BankReconcileMultiSelPrcRemote //javax.ejb.SessionBean
{
	ibase.webitm.utility.GenericUtility genericUtility =  ibase.webitm.utility.GenericUtility.getInstance();
	ibase.webitm.ejb.ITMDBAccessEJB itmDBAccessEJB = new ibase.webitm.ejb.ITMDBAccessEJB();
	
	ibase.utility.CommonConstants commonConstants = new ibase.utility.CommonConstants();
	
	java.sql.Connection conn = null;
	java.sql.PreparedStatement pstmt=null;
	java.sql.ResultSet rs=null;
	
	String bankCode =null;
	java.util.Vector BankStTranIdVec = new java.util.Vector();
	java.util.Vector BankTranLogVec = new java.util.Vector();
	
	/*public void ejbCreate() throws java.rmi.RemoteException, javax.ejb.CreateException
	{
		try
		{
			//conn = connDriver.getConnectDB("DriverITM");
			System.out.println("BankReconcileMultiSelPrcEJB ejbCreate called.........");
		}
		catch (Exception e)
		{
			System.out.println("Exception :BankReconcileMultiSelPrcEJB :ejbCreate :==>"+e);
			throw new javax.ejb.CreateException();
		} 
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	
	}*/

		
	
	public String process() throws java.rmi.RemoteException,ibase.webitm.utility.ITMException
	{
		return "";
	}
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws java.rmi.RemoteException,ibase.webitm.utility.ITMException
	{
		org.w3c.dom.Document headerDom = null;
		org.w3c.dom.Document detailDom = null;
		
		System.out.println("xmlString::::::::::::;"+ xmlString);
		System.out.println("xmlString2:::::::::::;"+ xmlString2);
		System.out.println("windowName:::::::::::;"+ windowName);
		System.out.println("xtraParams:::::::::::;"+ xtraParams);
		String  rtrStr ="";
		try 
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString);
				headerDom = genericUtility.parseString(xmlString); 				
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2); 				
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :BankReconcileMultiSelPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();
		}
		return rtrStr; 
	}//END OF GETDATA(1)
	public String getData(org.w3c.dom.Document headerDom, org.w3c.dom.Document detailDom, String windowName, String xtraParams) throws java.rmi.RemoteException,ibase.webitm.utility.ITMException
	{
			String errCode = "";
			String errString = null;
			String resultString = "";
			String getDataSql= "" ;
		
			StringBuffer retTabSepStrBuff = new StringBuffer();
			try
			{
				if(conn==null)
				{
					ibase.system.config.ConnDriver connDriver = new ibase.system.config.ConnDriver();
					conn = connDriver.getConnectDB("DriverITM");
					connDriver = null;
					
				}
			
			} 
			catch (Exception e)
			{
				System.out.println("Exception :BankReconcileMultiSelPrcEJB :ejbCreate :==>"+e);
			} 
			try
			{
				bankCode = genericUtility.getColumnValue("bank_code",headerDom);
				System.out.println("Processing Bankcode:::::::::::["+bankCode+"]");
				if ( bankCode == null || bankCode.trim().length() == 0 )
				{
					bankCode = "";
					System.out.println("bankCode From is Null...");
					errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","","",conn);
					return errString;
				} 
				getDataSql ="SELECT TRAN_ID,REF_NO,REF_DATE,AMOUNT,CURR_CODE,EXCH_RATE,TRAN_TYPE,REF_MODE,EFF_DATE,SITE_CODE,STAT_NO,STAT_DATE,AMT_ADJ,STATUS "
				+" FROM BANK_STATEMENT WHERE ( BANK_STATEMENT.BANK_CODE = '"+bankCode.trim()+"') AND  "
				+"( BANK_STATEMENT.STATUS = 'E' ) ORDER BY REF_NO ASC ";  
	 
				System.out.println("get Data Sql "+getDataSql);
				pstmt = conn.prepareStatement(getDataSql);
				
				//pstmt.setString(1,bankCode); 
		 		rs = pstmt.executeQuery();
				while(rs.next()) 
				{ 
					
							//TRAN_ID
							retTabSepStrBuff.append((rs.getString(1)==null?" ":rs.getString(1))).append("\t");
		 					//REF_NO
				         	retTabSepStrBuff.append((rs.getString(2)==null?" ":rs.getString(2))).append("\t");
							//REF_DATE
							retTabSepStrBuff.append(rs.getTimestamp(3)).append("\t");
							//AMOUNT(BC)
							retTabSepStrBuff.append(rs.getString(4)).append("\t");
							//CURR_CODE
							retTabSepStrBuff.append((rs.getString(5)==null?" ":rs.getString(5))).append("\t");
							//EXCH_RATE
							retTabSepStrBuff.append(rs.getString(6)).append("\t");
							//(AMOUNT/EXCHRATE)--AMOUNT
							//retTabSepStrBuff.append(rs.getDouble(4)/rs.getDouble(6)).append("\t");
							//retTabSepStrBuff.append("xxx").append("\t");
							//TRAN_TYPE
							retTabSepStrBuff.append((rs.getString(7)==null?" ":rs.getString(7))).append("\t"); 
							//REF_MODE
							retTabSepStrBuff.append((rs.getString(8)==null?" ":rs.getString(8))).append("\t");
							//EFF_DATE
							retTabSepStrBuff.append((rs.getString(9)==null?" ":rs.getString(9))).append("\t");
							//SITE_CODE
							retTabSepStrBuff.append((rs.getString(10)==null?" ":rs.getString(10))).append("\t");
							//STAT_NO
							retTabSepStrBuff.append((rs.getString(11)==null?" ":rs.getString(11))).append("\t");
							//STAT_DATE
							retTabSepStrBuff.append(rs.getTimestamp(12)).append("\t");
							
							//AMT_ADJ
							retTabSepStrBuff.append(rs.getString(13)).append("\t");
							//STATUS
							retTabSepStrBuff.append((rs.getString(14)==null?" ":rs.getString(14))).append("\t");
							
							retTabSepStrBuff.append("   ").append("\n");
			}
			rs.close();
			pstmt.close();
			System.out.println("retTabSepStrBuff:::::::::::::"+retTabSepStrBuff);
			resultString = retTabSepStrBuff.toString();
		}
		catch (java.sql.SQLException e)
		{
			System.out.println("SQLException :BankReconcileMultiSelPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ibase.webitm.utility.ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :BankReconcileMultiSelPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ibase.webitm.utility.ITMException(e);
		}
		finally
		{
			try
			{
				retTabSepStrBuff = null;
				if(conn != null)
				{					
					if(pstmt != null)
					{
						pstmt.close();
						pstmt=null;
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ibase.webitm.utility.ITMException(e);
			}
		}
		return resultString;	
	}//END OF GETDATA(2)
	//PROCESS
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws java.rmi.RemoteException,ibase.webitm.utility.ITMException
	{
			System.out.println("P R O C E S S I N G[UPDATE]......................");
		
			System.out.println("xmlString::::::::;;;"+xmlString);
			System.out.println("xmlString2:::::::;;;"+xmlString2);
			System.out.println("windowName:::::::;;;"+windowName);
			System.out.println("xtraParams:::::::;;;"+xtraParams);
			String retStr = "";
			org.w3c.dom.Document detailDom = null;
			org.w3c.dom.Document headerDom = null;
		
			try 
			{	
				if(xmlString != null && xmlString.trim().length()!=0)
				{
					headerDom = genericUtility.parseString(xmlString); 
				}
				if(xmlString2 != null && xmlString2.trim().length()!=0)
				{
					detailDom = genericUtility.parseString(xmlString2); 
				}
										
			    retStr = process(headerDom, detailDom, windowName, xtraParams);
			}
			catch (Exception e) 
			{
				System.out.println("Exception :BankReconcileMultiSelPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
				e.printStackTrace();
				retStr = e.getMessage();
			}
			return retStr;
		
	}//END OF PROCESS (1)
	public String process(org.w3c.dom.Document headerDom, org.w3c.dom.Document detailDom, String windowName, String xtraParams) throws java.rmi.RemoteException,ibase.webitm.utility.ITMException
	{
	
		bankCode = genericUtility.getColumnValue("bank_code",headerDom);
		System.out.println("Processing Bankcode:::::::::::["+bankCode+"]");
		org.w3c.dom.NodeList parentNodeList = null;
		org.w3c.dom.NodeList childNodeList = null;
		org.w3c.dom.Node parentNode = null;
		org.w3c.dom.Node childNode = null;
	
		String errString = null;;
		String tranIdBS =null;
		String tranIdBT =null;
		String sqlBS =null;
		String sqlBT =null;
		String sqlBS1 =null;
		//05062007
		String sqlBT1 =null;
		String tranIdBs = null;
		String	statusBS = null;
		String	statusBT =null;
		String BanktranLogTranIds=null;
		String childNodeName = "";
		
		int parentNodeListLength =0;
		int childNodeListLength = 0;
		
		
		double	amtBS	=0;
		double adjAmtBS  =0;
		double	balBS = 0;
		double	amtBT	= 0;
		double	adjAmtBT  =0;
		double	balBT =0;
		double amtAdjust=0;
		
		//ADDED MY MSALAM ON 14/0607
		int noOfBankLogTran = 0;
		int noOfBankStatement = 0;
		boolean isTranTypePAvailable = false;
		boolean isMulToMulOpr = false; 
		boolean isSameTypeOpr = true;
	
		java.sql.PreparedStatement pstmtBS=null;
		java.sql.ResultSet rsBS=null;
		java.sql.PreparedStatement pstmtBT=null;
		java.sql.ResultSet rsBT=null;
		
		StringBuffer btBuf = new StringBuffer();
		StringBuffer bsBuf = new StringBuffer();
		
		double bankStTot = 0;
		double bankTrTot = 0;
		
		try
		{
			if(conn==null)
			{
				ibase.system.config.ConnDriver connDriver = new ibase.system.config.ConnDriver();
				conn = connDriver.getConnectDB("DriverITM");
				connDriver = null;
			}
		
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			System.out.println("parentNodeListLength:::::::::"+parentNodeListLength);
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName(); 
					
					if (childNodeName.equals("tran_id"))
					{
						if(childNode.getFirstChild()!=null)
						{
							tranIdBS = childNode.getFirstChild().getNodeValue();
							if(!BankStTranIdVec.contains(tranIdBS.trim()))
							{
								BankStTranIdVec.add(tranIdBS.trim());
					 		}
						}
					}
					if (childNodeName.equals("banktran_log"))
					{
						if(childNode.getFirstChild()!=null)
						{
							BanktranLogTranIds = childNode.getFirstChild().getNodeValue();
							System.out.println("BanktranLogTranIds::::::::::::["+BanktranLogTranIds+"]");
							if(BanktranLogTranIds.trim().length()>0)
							{
								String[] token = BanktranLogTranIds.split(",");
								for(int i=0;i<token.length;i++)
								{
				 						if(!BankTranLogVec.contains(token[i].trim()))
										{
											BankTranLogVec.add(token[i].trim());
										}
								}
							}
						} 
					}
				}//INNER FOR LOOP	
			}
					
			//14062007
			noOfBankStatement = BankStTranIdVec.size();
		    noOfBankLogTran = BankTranLogVec.size();
		   //Commented by msalam on 18/06/07 as multiple processing on both side allowed. 
			/*
			if((BankStTranIdVec.size()>1) && (BankTranLogVec.size()>1) )
			{
				errString="MULSELNA";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				System.out.println("errString ::::["+errString+"]");
				return errString;
			}
			*/
			
			for(int i=0;i<BankStTranIdVec.size();i++)
			{
				tranIdBS = (String)BankStTranIdVec.get(i);
				if(i==BankStTranIdVec.size()-1)
		 		{
			 		bsBuf.append("'").append(tranIdBS).append("'");
			 		
		 		}
		 		else
		 		{	 		
			 		bsBuf.append("'").append(tranIdBS).append("'").append(",");
		 		}
				
			}
			for(int i=0;i<BankTranLogVec.size();i++)
			{
				tranIdBT = (String)BankTranLogVec.get(i);
				if(i==BankTranLogVec.size()-1)
		 		{
		 			btBuf.append("'").append(tranIdBT).append("'");
		 		}
		 		else
		 		{
		 			btBuf.append("'").append(tranIdBT).append("'").append(",");
		 		}
			
			}
			
			System.out.println("BankStatement[BUFFER] ::::"+bsBuf.toString());
			System.out.println("BankTranLog[BUFFER] ::::"+btBuf.toString());
	 	
		 
			//	ADDED ON 05062007	 
			int count = 0;
			//if the currency code not match of select record of bank statement then give error
			sqlBS1 = " SELECT COUNT(DISTINCT(CURR_CODE))  FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R'  ";
		
			pstmtBS = conn.prepareStatement(sqlBS1);
			rsBS = pstmtBS.executeQuery();
			if(rsBS.next()) 
			{
				count = rsBS.getInt(1); 
				
			}
			rsBS.close(); 
			pstmtBS.close(); 
			System.out.println("BankStatement[DISTINCT CURRENCY] ::"+sqlBS1+"["+count+"]");
			if(count!=1)
			{  
				
					errString="VTRECOCUR1";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					System.out.println("errString ::::["+errString+"]");
					return errString;
			}
				count =0;
			//if the currency code not match of select record of bank tran log then give error
			sqlBT1 = " SELECT COUNT(DISTINCT(CURR_CODE)) FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+btBuf.toString()+") and  status <> 'R'  ";
		
			pstmtBS = conn.prepareStatement(sqlBT1);
			rsBS = pstmtBS.executeQuery();
			if(rsBS.next()) 
			{
				count = rsBS.getInt(1);
				
			}
			rsBS.close(); 
			pstmtBS.close();
			System.out.println("BanktranLog[DISTINCT CURRENCY] ::"+sqlBT1+"["+count+"]");
		 
			if(count!=1)
			{				
					errString="VTRECOCUR2";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					System.out.println("errString ::::["+errString+"]");
					return errString;
			} 
			
			double amt =0;

			/////////////////////Dont allow Tran-type P & R together  for multiple to multiple operation
			if((BankStTranIdVec.size()>1) && (BankTranLogVec.size()>1) ){
				isMulToMulOpr = true;
				sqlBS1 = " SELECT COUNT(DISTINCT(TRAN_TYPE)) FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R'  ";
			
				pstmtBS = conn.prepareStatement(sqlBS1);
				rsBS = pstmtBS.executeQuery();
				if(rsBS.next()) 
				{
					count = rsBS.getInt(1); 
					
				}
				rsBS.close(); 
				pstmtBS.close(); 
				System.out.println("BankStatement[DISTINCT TRAN_TYPE] ::"+sqlBS1+"["+count+"]");
				if(count!=1)
				{  
					
						errString="MULTTNA1";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						System.out.println("errString ::::["+errString+"]");
						return errString;
				}
					count =0;
				//if the TRAN_TYPE not match of select record of bank tran log then give error
				sqlBT1 = " SELECT COUNT(DISTINCT(TRAN_TYPE)) FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+btBuf.toString()+") and  status <> 'R'  ";
			
				pstmtBS = conn.prepareStatement(sqlBT1);
				rsBS = pstmtBS.executeQuery();
				if(rsBS.next()) 
				{
					count = rsBS.getInt(1);
					
				}
				rsBS.close(); 
				pstmtBS.close();
				System.out.println("BanktranLog[DISTINCT TRAN_TYPE] ::"+sqlBT1+"["+count+"]");
			 
				if(count!=1)
				{
					
						errString="MULTTNA2";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						System.out.println("errString ::::["+errString+"]");
						return errString;
				} 
				
				sqlBS1 = " SELECT sum(AMOUNT-AMT_ADJ), TRAN_TYPE FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R'  GROUP BY TRAN_TYPE ";
				sqlBT1 = " SELECT sum(AMOUNT-AMT_ADJ), TRAN_TYPE FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+btBuf.toString()+") and  status <> 'R'  GROUP BY TRAN_TYPE ";
	
				//sqlBS1 = " SELECT AMOUNT-AMT_ADJ, TRAN_TYPE FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R'  ";
				//sqlBT1 = " SELECT AMOUNT-AMT_ADJ, TRAN_TYPE FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+btBuf.toString()+") and  status <> 'R'  ";
	
				System.out.println("BankStatement Amount[SQL] ::"+sqlBS1);
				System.out.println("BankTranLog Amount[SQL] ::::"+sqlBT1);
			
				pstmtBS = conn.prepareStatement(sqlBS1);
				rsBS = pstmtBS.executeQuery();
	
				String tranTypeBS = null;
				String tranTypeBT = null;
				
				String positiveType = null;
							    
		    	if(rsBS.next()){
			    	amt = 0;
					amt = rsBS.getDouble(1);
					tranTypeBS = rsBS.getString(2);
					bankStTot = amt;
				}
				
				pstmtBT = conn.prepareStatement(sqlBT1);
				rsBT = pstmtBT.executeQuery();
	
		    	if(rsBT.next()){
			    	amt = 0;
					amt = rsBT.getDouble(1);
					tranTypeBT = rsBT.getString(2);
					positiveType = tranTypeBT;
					bankTrTot = amt;
				}
				if(!(tranTypeBS.equalsIgnoreCase(tranTypeBT)))
				{
						System.out.println("TRAN_TYPE Miss Match ***************");
						errString="DTTNA";
						errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
						System.out.println("errString ::::["+errString+"]");
						return errString;
				}
			}
			else{
				//For one to multiple operation
				sqlBS1 = " SELECT AMOUNT-AMT_ADJ, TRAN_TYPE FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R'  ";
				sqlBT1 = " SELECT AMOUNT-AMT_ADJ, TRAN_TYPE FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+btBuf.toString()+") and  status <> 'R'  ";
				
				pstmtBS = conn.prepareStatement(sqlBS1);
				rsBS = pstmtBS.executeQuery();
				pstmtBT = conn.prepareStatement(sqlBT1);
				rsBT = pstmtBT.executeQuery();
				String tranTypeBs = null;
				String tranTypeBT = null;
				
				String positiveType = null;

				if(noOfBankStatement == 1){		    
			    	if(rsBS.next()){
				    	amt = 0;
						amt = rsBS.getDouble(1);
						tranTypeBs = rsBS.getString(2);
						positiveType = tranTypeBs;
						bankStTot = amt;
					}
			  	}
			    if(noOfBankLogTran == 1){		    
			    	if(rsBT.next()){
				    	amt = 0;
						amt = rsBT.getDouble(1);
						tranTypeBT = rsBT.getString(2);
						positiveType = tranTypeBT;
						bankTrTot = amt;
					}
			  	}

			    if(noOfBankLogTran == 1)
					while(rsBS.next()) 
					{
						amt =0;
						amt = rsBS.getDouble(1);
						tranTypeBs = rsBS.getString(2);
						if(positiveType.equalsIgnoreCase(tranTypeBs))
						{
							bankStTot = bankStTot + amt;
						}
						else
						{
							bankStTot = bankStTot - amt;
							isTranTypePAvailable = true;
	
						}
					}
				
				if(noOfBankStatement == 1)			
					while(rsBT.next()) 
					{
						amt =0;
						amt = rsBT.getDouble(1);
						tranTypeBT = rsBT.getString(2);
						if(positiveType.equalsIgnoreCase(tranTypeBT))
						{
							bankTrTot = bankTrTot + amt;
						}
						else
						{
							bankTrTot = bankTrTot - amt;
							isTranTypePAvailable = true;
						}
					}
			}//End of else
			
			if(isTranTypePAvailable == true)//Operation is not have same tran type on both sides
				isSameTypeOpr = false;
				
			rsBS.close(); 
			pstmtBS.close(); 
						
			rsBT.close();
			pstmtBT.close();
			
			System.out.println("BankStTot ::::["+bankStTot+"]");
			System.out.println("bankTrTot ::::["+bankTrTot+"]");

			if(bankTrTot != bankStTot)
			{
					System.out.println("Amount Miss Match ***************");
					errString="AMTMISS";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					System.out.println("errString ::::["+errString+"]");
					return errString;
			}
	
			// END 05062007

			sqlBS = " SELECT TRAN_ID,AMOUNT,AMT_ADJ,STATUS, TRAN_TYPE FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R' order by tran_id ";
			sqlBT = " SELECT TRAN_ID,AMOUNT,AMT_ADJ,STATUS, TRAN_TYPE FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"' and TRAN_ID IN ("+btBuf.toString()+") and status <> 'R' order by tran_id ";								
			String tempErrStr = null;
			
			if( isSameTypeOpr == false){//Operation has same tran type on both sides
				Object recoArray[];
				Reco rec = null;
				String errStr = null;
				String recoTable = null;
				///////////////////////
				try{
				
				    if(noOfBankStatement != 1){
				    	recoTable = "STATEMENT";
						recoArray = reconcile(sqlBS, recoTable);
						
						System.out.println("recoArr.len in stat :: " + recoArray.length);
						System.out.println("After recoArray = reconcile(sqlBS)");
						for(int updCounter = 0; updCounter < recoArray.length ; updCounter++){
							rec = (Reco)recoArray[updCounter];
							errStr = updateBankStatement(rec.tranId, rec.adjAmt, rec.status);
						}
					}
					if(noOfBankLogTran != 1){	
						//Log to Log reconciliation
						recoTable = "TRANLOG";
						System.out.println("Before recoArray = reconcile(sqlBS)");
						recoArray = reconcile(sqlBT, recoTable);
						System.out.println("recoArr.len in lot :: " + recoArray.length);
						System.out.println("After recoArray = reconcile(sqlBS)");
						for(int updCounter = 0; updCounter < recoArray.length ; updCounter++){
							rec = (Reco)recoArray[updCounter];
							errStr = updateBankTranLog(rec.tranId, rec.adjAmt, rec.status);
						}
						//End of Log to Log reconciliation
					}
				}catch(Exception ex){
					ex.printStackTrace();
					errString="SPRECOERR";
					errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
					return errString;
				}
				//End of statement to statement reconciliation
				//////////////////////
			}	
			
			System.out.println("Processing for SAME TYPE BOTH THE SIDE");
			//sqlBS = " SELECT TRAN_ID,AMOUNT,AMT_ADJ,STATUS FROM BANK_STATEMENT  WHERE BANK_CODE ='"+bankCode.trim()+"'  and TRAN_ID IN ("+bsBuf.toString()+") and  status <> 'R' order by tran_id ";
			//sqlBT = " SELECT TRAN_ID,AMOUNT,AMT_ADJ,STATUS FROM BANKTRAN_LOG  WHERE BANK_CODE ='"+bankCode.trim()+"' and TRAN_ID IN ("+btBuf.toString()+") and status <> 'R' order by tran_id ";
			
			System.out.println("BankStatement[SQL] ::" + sqlBS);
			System.out.println("BankTranLog[SQL] ::::" + sqlBT);
			
			pstmtBS = conn.prepareStatement(sqlBS);
			rsBS = pstmtBS.executeQuery();
			pstmtBT = conn.prepareStatement(sqlBT);

			while(rsBS.next())
			{
				balBS = 0.0;
				
				tranIdBs = rsBS.getString(1);
				amtBS	= rsBS.getDouble(2);
				adjAmtBS  =rsBS.getDouble(3);
				statusBS = rsBS.getString(4);
				balBS = amtBS - adjAmtBS;
				
				System.out.println("Bank Stat amtBs[" + amtBS + "]");
				System.out.println("Bbalance in adjAmtBs[" + adjAmtBS + "]");
				System.out.println("Bbalance in statusBS[" + statusBS + "]");

				System.out.println("Bank Stat Tran Id["+tranIdBs+"]");
				System.out.println("Bbalance in bank_statement["+balBS+"]");
				
				rsBT = pstmtBT.executeQuery();
							
				statusBT = " ";
				statusBS = " ";
				tempErrStr = "";
				while(rsBT.next() && !statusBS.equalsIgnoreCase("R"))
				{
					
					String tStatusBT = null;
					balBT = 0.0;
					tranIdBT = rsBT.getString(1);
					amtBT	= rsBT.getDouble(2);
					adjAmtBT  =rsBT.getDouble(3);
					statusBT = rsBT.getString(4);
					tStatusBT = statusBT;
					balBT = amtBT - adjAmtBT;
					System.out.println("--BS Tran = " + tranIdBs + "  BS Log = " + tranIdBT + "  --");															
					System.out.println("Comparing Against["+tranIdBs+"]");
					System.out.println("Bank Log Id["+tranIdBT+"]");
					System.out.println("Bbalance in bank_tranlog["+balBS+","+balBT+"]");
				 
					if(balBS == balBT)
					{
						amtAdjust = balBS;
						statusBS = "R"; 
						statusBT = "R";
						System.out.println("AmtAdjust To be adjust (balBS ==balBT):::["+amtAdjust+"]");
					}
					else if(balBS > balBT)
					{
						amtAdjust = balBT;
						statusBT = "R";	
						statusBS = "P"; 
						System.out.println("AmtAdjust To be adjust (balBS >balBT):::["+amtAdjust+"]");
					}
					else if (balBS < balBT)
					{
						amtAdjust = balBS;
						statusBS = "R";
						statusBT = "P";	
						System.out.println("AmtAdjust To be adjust (balBS < balBT):::["+amtAdjust+"]");
					}
					adjAmtBT = adjAmtBT + amtAdjust;
					adjAmtBS = adjAmtBS + amtAdjust;

					tempErrStr = insertBankRecoTrace(tranIdBs, tranIdBT, amtAdjust);
					if(tempErrStr.length() != 0){
						System.out.println("insertBankRecoTrace error :: " + tempErrStr);
						break;
					}
			
					tempErrStr = updateBankTranLog(tranIdBT, adjAmtBT, statusBT);
					if(tempErrStr.length() != 0){
						System.out.println("updateBankTranLog error :: " + tempErrStr);
						break;
					}

					tempErrStr = updateBankStatement(tranIdBs,adjAmtBS,statusBS);
					if(tempErrStr.length() != 0){
						System.out.println("updateBankStatement error :: " + tempErrStr);
						break;
					}
					 
					balBS = balBS - amtAdjust;
						
					System.out.println("DIFFERENT :::["+balBS+"]");
					//14062007
					//	if(balBS<= 0)
					//	break;
				}//End of rsBT.next()
				
				System.out.println("TEMP ERR STR = " + tempErrStr);
				
				System.out.println("End of --BS Tran = " + tranIdBs + "  BS Log = " + tranIdBT + "  --");
				if(tempErrStr.length() != 0){
					errString = tempErrStr;
					break;
				}
			}//End of rsBS.next()

			pstmtBS.close();
			pstmtBT.close();
			if (errString == null || errString.trim().length() == 0)
			{	
				try{
					conn.commit();
				}catch(Exception ex){}
			
				System.out.println("errString is null************** ");
				errString="VTCOMPL";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;
			}
			else
			{
				System.out.println("errString is not  null ***************");
				errString="VTPRCERR";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;
			}
						
		}
		catch(Exception e)
		{
				System.out.println("Exception :BankReconcileMultiSelPrcEJB :process(String xmlString2, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
				e.printStackTrace();
				errString="MAINERR1";
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;
				//throw new ibase.webitm.utility.ITMException(e);
		} 
		finally
		{
			System.out.println("Closing Connection...."+errString);
			try
			{ 
				BankTranLogVec.clear();
				BankStTranIdVec.clear();

				if(conn != null)
				{				
					conn.close();
					conn = null; 
				}
			}
			catch(Exception e)
			{
				errString = "MAINERR2";
				e.printStackTrace();
				errString = itmDBAccessEJB.getErrorString("",errString,"","",conn);
				return errString;
			}	
		}
	}//END OF PROCESS(2)
	
	
	private String updateBankStatement(String tranId,double adjAmt,String status)
	{
		java.sql.PreparedStatement upstmt = null;
		String 	update ="";
		String errString = "";
		System.out.println("Update BankStatement------------->>>");
		System.out.println("TranId:::["+tranId+"]");
		System.out.println("Status:::["+status+"]");
		System.out.println("AdjAmt:::["+adjAmt+"]");
		System.out.println(" In Stat StId, Status, Amt :: " + tranId + ", " + status + ", " + adjAmt);
		try
		{ 
		 	update = " UPDATE BANK_STATEMENT SET STATUS = '"+status+"', AMT_ADJ = "+adjAmt+" WHERE TRAN_ID = '"+tranId+"'  ";		
			upstmt = conn.prepareStatement(update);
			//upstmt.setString(1,status);
			//upstmt.setDouble(2,adjAmt);	
			//upstmt.setString(3,tranId.trim());			
			//upstmt.setString(4,refno.trim());
			int u = upstmt.executeUpdate();
			System.out.println("No of record update in BankStatement:::["+u+"]");
			upstmt.close();
			//conn.commit();
		}
		catch(java.sql.SQLException seUpdate)
		{
			errString = "UPDBSERR1";
			System.out.println("SQLException(Update BankStatement) :[Excuting Query Failed ]" + update + seUpdate.getMessage());
		}
		catch(Exception exUpdate)
		{
			errString = "UPDBSERR2";
			System.out.println("Exception3(Update BankStatement) ::"+update +exUpdate.getMessage());
			exUpdate.printStackTrace();
		}
		return errString;
	}
	
	//updateBankTranLog
	private String updateBankTranLog(String tranId,double adjAmt,String status)
	{
		java.sql.PreparedStatement upstmt = null;
		String update ="";
		String errString = "";
		System.out.println("Update BankTranLog--------------->>>");
		//System.out.println("TranId:::["+tranId+"]");
		//System.out.println("Status:::["+status+"]");
		//System.out.println("AdjAmt:::["+adjAmt+"]");
		System.out.println(" In Bank Lot TrId, Status, Amt :: " + tranId + ", " + status + ", " + adjAmt);
		try
		{ 
			update = " UPDATE BANKTRAN_LOG SET STATUS = '"+status+"', AMT_ADJ = "+adjAmt+" WHERE TRAN_ID = '"+tranId+"'  ";		
			upstmt = conn.prepareStatement(update);
			//upstmt.setString(1,status);
			//upstmt.setDouble(2,adjAmt);				
			//upstmt.setString(3,tranId.trim());	
			//upstmt.setString(4,refno.trim());	
			int u = upstmt.executeUpdate();
			System.out.println("No of record update in banktran_log:::["+u+"]");
			upstmt.close();
			//conn.commit();
		}
		catch(java.sql.SQLException seUpdate)
		{
			errString = "UPDBTLBSERR1";
			System.out.println("SQLException(Update BankTranLog) :[Excuting Query Failed ]" + update + seUpdate.getMessage());
		}
		catch(Exception exUpdate)
		{
			errString = "UPDBTLBSERR1";
			System.out.println("Exception3(Update BankTranLog) ::"+update +exUpdate.getMessage());
			exUpdate.printStackTrace();
		}
		return errString;
	}
	
	private String insertBankRecoTrace(String tranIdBS,String tranIdBT,double adjAmount)
	{
		java.sql.PreparedStatement ipstmt = null;
		String 	insert = "";
		String errString = "";
		//System.out.println("TranId(BankStatement):::["+tranIdBS+"]");
		//System.out.println("TranId(BankTransaction):::["+tranIdBT+"]");
		//System.out.println("AdjAmt:::"+adjAmount);
		System.out.println("StId, TrId, Amt :: " + tranIdBS + ", " + tranIdBT + ", " + adjAmount);
		try 
		{ 
		 	insert = " INSERT INTO BANKRECO_TRACE (TRAN_ID__STAT, TRAN_ID__LOG, AMOUNT ) VALUES (?,?,?)";
			ipstmt = conn.prepareStatement(insert);
			ipstmt.setString(1,tranIdBS);
			ipstmt.setString(2,tranIdBT);				
			ipstmt.setDouble(3,adjAmount);	
			
			System.out.println("Insert a record in Trace---------------->>>["+ipstmt.executeUpdate()+"]");
			ipstmt.close();
			//conn.commit();
		}
		catch(java.sql.SQLException seinsert)
		{
			errString = "INSBRTERR1";
			System.out.println("SQLException(insert in to Trace) :[Excuting Query Failed ]" + insert + seinsert.getMessage());
		}
		catch(Exception exinsert)
		{
			errString = "INSBRTERR2";
			System.out.println("Exception(insert in to Trace) ::"+insert +exinsert.getMessage());
			exinsert.printStackTrace();
		}
		return errString;
	}
	
	//added by ms alam on 22/06/07
	private String insertBankRecoTrace(String tranIdBS,String tranIdBT, double amount, double amountSt, double amountLog)
	{	//insertBankRecoTrace(fromStatId, toStatId, 0, amtAdjust, 0);
		java.sql.PreparedStatement ipstmt = null;
		String 	insert = "";
		String errString = "";
		//System.out.println("TranId(BankStatement):::["+tranIdBS+"]");
		//System.out.println("TranId(BankTransaction):::["+tranIdBT+"]");
		//System.out.println("AdjAmt:::"+adjAmount);
		System.out.println("StId, TrId, Amt, AmtSt, AmtLog :: " + tranIdBS + ", " + tranIdBT + ", " + amount + ", " + amountSt + ", " + amountLog);
		try 
		{ 
		 	insert = " INSERT INTO BANKRECO_TRACE (TRAN_ID__STAT, TRAN_ID__LOG, AMOUNT, amount_ST, amount_Log ) VALUES (?,?,?,?,?)";
			ipstmt = conn.prepareStatement(insert);
			ipstmt.setString(1, tranIdBS);
			ipstmt.setString(2, tranIdBT);				
			ipstmt.setDouble(3, amount);	
			ipstmt.setDouble(4, amountSt);	
			ipstmt.setDouble(5, amountLog);	
			
			System.out.println("Insert a record in Trace---------------->>>["+ipstmt.executeUpdate()+"]");
			ipstmt.close();
			//conn.commit();
		}
		catch(java.sql.SQLException seinsert)
		{
			errString = "INSBRTERR4";
			System.out.println("SQLException(insert in to Trace) :[Excuting Query Failed ]" + insert + seinsert.getMessage());
		}
		catch(Exception exinsert)
		{
			errString = "INSBRTERR5";
			System.out.println("Exception(insert in to Trace) ::"+insert +exinsert.getMessage());
			exinsert.printStackTrace();
		}
		return errString;
	}

	//end of bank reco trace by ms alam
	
	
	
	
	private Object[] reconcile(String sql, String forTable) throws Exception{
		String tranIdBS = "";
		double amtBS = 0.0;
		double adjAmtBS = 0.0;
		String statusBS = "";
		double balBS = 0.0;
		String tranTypeBS = "";

		double amtAdjust = 0.0;

		String tranIdBT = "";
		double amtBT = 0.0;
		double adjAmtBT = 0.0;
		String statusBT = "";
		double balBT = 0.0;
		String tranTypeBT = "";

		String fromStatId = null, toStatId = null;
		
		String errStr = null;
	
		java.sql.PreparedStatement pstmt=null;
		java.sql.ResultSet rs=null;
	
		pstmt = conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		
		List recoList = new ArrayList();
		
		while(rs.next())
		{	
			balBS = 0.0;
			tranIdBS = rs.getString(1);
			amtBS = rs.getDouble(2);
			adjAmtBS  =rs.getDouble(3);
			statusBS = rs.getString(4);
			tranTypeBS = rs.getString(5);
			
			balBS = amtBS - adjAmtBS;	

			//Reco(String tranId, double amt, double adjAmt, String status, String tranType)
			
			Reco rec = new Reco(tranIdBS, amtBS, adjAmtBS, statusBS, tranTypeBS);
			recoList.add(rec);			
		}
		
		Object statArray[] = (Object [])recoList.toArray();		
		
		Reco fromRec = null;
		Reco toRec = null;
		System.out.println("statArr.len in reco ::: " + statArray.length);	
		for(int fromCounter = 0; fromCounter < statArray.length; fromCounter++)
		{
			fromRec = (Reco)statArray[fromCounter];
			
			balBS = 0.0;
			tranIdBS = fromRec.tranId;//statArray[fromCounter].tranId;
			amtBS = fromRec.amt; //statArray[fromCounter].amt;
			adjAmtBS = fromRec.adjAmt; //statArray[fromCounter].adjAmt;
			statusBS = fromRec.status; //fromRec.statArray[fromCounter].status;
			tranTypeBS = fromRec.tranType; //statArray[fromCounter].tranType;
			balBS = amtBS - adjAmtBS;
									
			statusBS = " ";
			
			for(int toCounter = fromCounter + 1; 
					toCounter < statArray.length && !(fromRec.status.equals("R")); 
					toCounter++)
			{				
				toRec = (Reco)statArray[toCounter];
				
				balBT = 0.0;
				
				tranIdBT = toRec.tranId;
				amtBT = toRec.amt;
				adjAmtBT = toRec.adjAmt;
				statusBT = toRec.status;
				tranTypeBT = toRec.tranType;
				balBT = amtBT - adjAmtBT;
				amtAdjust = 0.0;

				if(!((fromRec.tranType).equals(toRec.tranType)) && !statusBT.equals("R")){
					System.out.println("In fromRec.tranType).equals(toRec.tranType ");		
					if(balBS == balBT)
					{
						amtAdjust = balBS;
						statusBS = "R"; 
						statusBT = "R";
						//insert trace (fromTranId, toTranId, amount =0, amount_st = balBT)
						fromStatId = fromRec.tranId;
						toStatId = toRec.tranId;

						//update stat (fromTranId, adjAmt = balBT, status = R)
						fromRec.adjAmt = balBT;
						fromRec.status = "R";
						//End of update stat (fromTranId, adjAmt = balBT, status = R)
						
						//update stat (toTranId, adjAmt = balBT, status = R);
						toRec.adjAmt = balBT;
						toRec.status = "R";						
						//End of update stat (toTranId, adjAmt = balBT, status = R);
						System.out.println("AmtAdjust To be adjust (balBS ==balBT):::["+amtAdjust+"]");
					}
					else if(balBS > balBT)
					{
						amtAdjust = balBT;
						statusBT = "R";	
						statusBS = "P"; 
						fromStatId = fromRec.tranId;
						toStatId = toRec.tranId;
						//insert trace (fromTranId, toTranId, amount =0, amount_st = balBT)
						
						//update stat (fromTranId, adjAmt = balBT, status = P)
						fromRec.adjAmt += balBT;
						fromRec.status = "P";
						//End of update stat (fromTranId, adjAmt = balBT, status = R)
						
						//update stat (toTranId, adjAmt = balBT, status = R);
						toRec.adjAmt = balBT;
						toRec.status = "R";						
						//End ofupdate stat (toTranId, adjAmt = balBT, statur = R);

						System.out.println("AmtAdjust To be adjust (balBS >balBT):::["+amtAdjust+"]");
					}
					else if (balBS < balBT)
					{
						amtAdjust = balBS;
						statusBS = "R";
						statusBT = "P";
						//insert trace (fromTranId, toTranId, amount =0, amount_st = balBS)

						fromStatId = fromRec.tranId;
						toStatId = toRec.tranId;

						//uupdate stat (fromTranId, adjAmt = balBT, status = R)
						fromRec.adjAmt += balBS;
						fromRec.status = "R";
						//End of update stat (fromTranId, adjAmt = balBT, status = R)
						
						//update stat (toTranId, adjAmt = balBT, status = R);
						toRec.adjAmt += balBS;
						toRec.status = "P";						
						//End of update stat (toTranId, adjAmt = balBT, statur = P); 
						System.out.println("AmtAdjust To be adjust (balBS < balBT):::["+amtAdjust+"]");
					}
					if(forTable.equals("STATEMENT"))
						errStr = insertBankRecoTrace(fromStatId, toStatId, 0, amtAdjust, 0);
					else if(forTable.equals("TRANLOG"))
							errStr = insertBankRecoTrace(fromStatId, toStatId, 0, 0, amtAdjust);

					if(errStr != null && errStr.length() != 0){
						throw new Exception();	
					}
				}//End of tranType not equal it
			}//End of inner for loop
			if(errStr != null && errStr.length() != 0){
				throw new Exception();
			}
		}//End of outer for loop		
		return statArray;
	}//End of Statement To Statement Reco
	//added by msalam on 22/06/07
	private class Reco{
		public String tranId = "";
		public double amt = 0.0;
		public double adjAmt = 0.0;
		public String status = "";	
		public String tranType = "";
		public double bal = 0.0;
		
		public Reco(String tranId, double amt, double adjAmt, String status, String tranType){
			this.tranId = tranId;
			this.amt = amt;
			this.adjAmt = adjAmt;
			this.status = status;
			this.tranType = tranType;
			this.bal = amt - adjAmt;
		}
	}	
	
}//END OF EJB
