/*
    Window Name : w_bank_reconciliation
	Button Name : Process
	Action		: It Select data from BANK_STATEMENT and after that 
				  Insert into BANKRECO_TRACE,Also Update STATUS Field of BANK_STATEMENT Table. 	              
*/

package ibase.webitm.ejb.fin.adv;

import java.rmi.RemoteException;
import java.util.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.ejb.*;

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

@Stateless // added for ejb3

public class BankStartRecoPrc extends ProcessEJB implements BankStartRecoPrcLocal,BankStartRecoPrcRemote // SessionBean
{
  	/*public void ejbCreate() throws RemoteException, CreateException
	{
		try
		{
			System.out.println("BankReconciliationEJB ejbCreate called.........");
			
		}
		catch (Exception e)
		{
			System.out.println("Exception :BankReconciliationEJB :ejbCreate :==>"+e);
			throw new CreateException();
		}
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		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 :BankRecoEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		return rtrStr; 
	}

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String getDataSql = "";
		String bankCode = "";
		String resultString = "";
		String errCode = "";
		Connection conn = null;
		ResultSet rs = null;
		Statement stmt = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
	    ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			bankCode = genericUtility.getColumnValue("bank_code",headerDom);
			getDataSql = "SELECT BANK_STATEMENT.TRAN_ID,"   
				         +"BANK_STATEMENT.SITE_CODE,"   
						 +"BANK_STATEMENT.REF_NO,"   
						 +"BANK_STATEMENT.REF_DATE,"   
						 +"BANK_STATEMENT.REF_MODE,"   
						 +"BANK_STATEMENT.AMOUNT,"   
						 +"BANK_STATEMENT.TRAN_TYPE,"   
						 +"BANK_STATEMENT.STAT_NO,"   
						 +"BANK_STATEMENT.STAT_DATE,"   
						 +"BANK_STATEMENT.STATUS,"   
						 +"BANK_STATEMENT.AMT_ADJ,"   
						 +"BANK_STATEMENT.EFF_DATE,"   
						 +"BANK_STATEMENT.EXCH_RATE,"   
						 +"BANK_STATEMENT.CURR_CODE,"   
						 +"BANK_STATEMENT.REMARKS"  
						 +" FROM BANK_STATEMENT"  
						 +" WHERE ( bank_statement.bank_code = '"+ bankCode +"'"+" )"
						 +" AND ( bank_statement.status = 'E' )"   
						 +"	ORDER BY BANK_STATEMENT.REF_NO ASC";
			System.out.println("The getDataSql becomes :"+getDataSql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(getDataSql);
			if (rs.next())
			{
				do
				{
					retTabSepStrBuff.append(rs.getString(1)).append("\t");
					retTabSepStrBuff.append(rs.getString(2)).append("\t");
					retTabSepStrBuff.append(rs.getString(3)).append("\t");
					retTabSepStrBuff.append(rs.getString(4)).append("\t");
					retTabSepStrBuff.append(rs.getString(5)).append("\t");
					retTabSepStrBuff.append(rs.getString(6)).append("\t");
					retTabSepStrBuff.append(rs.getString(7)).append("\t");
					retTabSepStrBuff.append(rs.getString(8)).append("\t");
					retTabSepStrBuff.append(rs.getString(9)).append("\t");
					retTabSepStrBuff.append(rs.getString(10)).append("\t");
					retTabSepStrBuff.append(rs.getString(11)).append("\t");
					retTabSepStrBuff.append(rs.getString(12)).append("\t");
					retTabSepStrBuff.append(rs.getString(13)).append("\t");
					retTabSepStrBuff.append(rs.getString(14)).append("\t");
					retTabSepStrBuff.append(rs.getString(15)).append("\n");
				}while(rs.next());
				resultString = retTabSepStrBuff.toString();
			}
			else
			{
				errCode ="VTNOREC2";
			}
			if (!errCode.equals(""))
			{
				resultString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				System.out.println("resultString: "+resultString);
			}
		}
		catch (SQLException e)
		{
			System.out.println("Exception :BankReconciliationEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :BankReconciliationEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception e){}
		}		
		return resultString;	
	}


	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		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 :BankRecoEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String amount = "";
		String tranType = "";
		String errCode = "";
		String tranId = "";
		String insertSql = "";
		String childNodeName = "";
		String errString = "",updateSql = "";
		ArrayList tranIdList = new ArrayList();
		ArrayList amountList = new ArrayList();
		Connection conn = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmt1 = null;
		double amount1 = 0;
		double totalAmount = 0;
		int intCnt = 0;
		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
	    ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			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("amount"))
					{
						amount = childNode.getFirstChild().getNodeValue();
						if (amount == null)
						{
							amount1 = 0;
						}
						else
						{
							amount1 = Double.parseDouble(amount);
						}
						amountList.add(selectedRow, new Double(amount1));
					}
					if (childNodeName.equals("tran_type"))
					{
						tranType = childNode.getFirstChild().getNodeValue();
						if (tranType.equals("R"))
						{
							totalAmount = totalAmount + amount1;
							System.out.println("totalAmount :"+totalAmount);
						}
						else
						{
							totalAmount = totalAmount - amount1;
							System.out.println("totalAmount :"+totalAmount);
						}
					}
					if (childNodeName.equals("tran_id"))
					{
						tranId = childNode.getFirstChild().getNodeValue();
						tranIdList.add(selectedRow, tranId);
					}
				}//end inner for
			}//end outer for 
			System.out.println("totalAmount :"+totalAmount);
			if (totalAmount == 0)
			{
				System.out.println("tranIdList.size() :"+tranIdList.size());
				insertSql = "INSERT INTO BANKRECO_TRACE(TRAN_ID__LOG, TRAN_ID__STAT, AMOUNT)"
					+" VALUES ( ?, ?, ?)";
				pstmt = conn.prepareStatement(insertSql);
				updateSql = "UPDATE BANK_STATEMENT SET STATUS = ?,"
						+" AMT_ADJ = AMOUNT WHERE TRAN_ID = ?";
				pstmt1 = conn.prepareStatement(updateSql);
				for (int cnt = 0; cnt < tranIdList.size(); cnt++)
				{					
					System.out.println("Insert Sql :"+insertSql);
					pstmt.setString(1, " ");
					pstmt.setString(2, tranIdList.get(cnt).toString());
					pstmt.setDouble(3, Double.parseDouble(amountList.get(cnt).toString()));
					intCnt = pstmt.executeUpdate();
					System.out.println("intCnt :"+intCnt);
					if (intCnt == 0)
					{
						errCode = "ADS0001400";
						break;
					}
					else if (intCnt > 0)
					{
						System.out.println("Update Sql :"+updateSql);
						pstmt1.setString(1,"R");
						pstmt1.setString(2, tranIdList.get(cnt).toString());
						updCnt = pstmt1.executeUpdate();
						System.out.println("updCnt :"+updCnt);
						if (updCnt == 0)
						{
							errCode = "VTADHOC1";
							break;
						}						
					}
					pstmt.clearParameters();
					pstmt1.clearParameters();
				}//end for
			}//end if
			if (errCode.equals("") || errCode.trim().length() == 0)
			{
				errCode = "VMSUCC";
				conn.commit();
			}
			else
			{
				conn.rollback();
			}
			if (errCode != null || errCode.trim().length() > 0)
			{
				errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);			
			}			
		}//end try
		catch(Exception e)
		{
			System.out.println("Exception :BankStartRecoEJB :process(String xmlString2, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			System.out.println("Closing Connection....");
			try
			{
				conn.close();
				conn = null;
			}catch(Exception se){}
		}
		System.out.println("errString: "+errString);	
		return errString;
	}	
}