package ibase.webitm.ejb.fin.adv;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.util.*;
import java.text.*;
import java.sql.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import ibase.system.config.AppConnectParm;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.rmi.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class BankRecoSingleAct extends ActionHandlerEJB implements BankRecoSingleActLocal,BankRecoSingleActRemote // SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	String lsCurrcode = null;
	String errorString = null;
	String processErrString = null;
	String userid ="", loginSite = "", empCode= "", termid="";
	/*public void ejbCreate() throws RemoteException, CreateException
	{
		System.out.println("Create Method Called....");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}*/
	public String actionHandler() throws RemoteException, ITMException
	{
		System.out.println("actionHandler() Method Called....");
		return "";
	}
	public String actionHandler(String xmlString, String xtraParams, String objContext) throws RemoteException, ITMException
	{
		String  retString = null;
		System.out.println("Xtra Params : " + xtraParams);
		//genericUtility = GenericUtility.getInstance();
		try
		{
			retString = actionConfirm(xmlString, xtraParams);
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :actionHandler(String xmlString):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning from  actionHandler"+retString);
	    return (retString);
	}
	private String actionConfirm(String xmlString, String xtraParams) throws RemoteException,ITMException, Exception
	{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		Document headerDom = null;
		System.out.println("xmlString ...."+xmlString );
		userid = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
		loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
		empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
		termid = genericUtility.getValueFromXTRA_PARAMS(xtraParams, "termId");
		System.out.println("empCode.......... !"+empCode);
		String sql = "";
        String retString = "";
		String errString = null;
		int count = 0, i = 0, upd = 0;
		System.out.println("xmlString ...."+xmlString );
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			String errStr = null;
			
			System.out.println( "Tran Id :: " + xmlString );
			errStr = reconcile( xmlString, conn );
			
			if( errStr != null && errStr.trim().length() > 0 )
			{
				conn.rollback();			
			}
			else
			{
				conn.commit();
				retString = "VTRECOSUC";
			}
			errString = itmDBAccessEJB.getErrorString( "", retString, userid, "", conn );
		}
		catch(Exception e)
		{
			System.out.println( "BankRecoSingleActEJB..." + e.getMessage() );
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
			   System.out.println( "BankRecoSingleActEJB..." + e1.getMessage() );
			   e1.printStackTrace();
			}
		}
		finally
		{
			try
			{
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
				
			}
			catch(Exception e)
			{
				System.out.println("Exception ConfirmMPSOrderEJB....... :\n"+e.getMessage());
			}
		}
		System.out.println("retString ::"+errString);
		return errString;
	}
	private String reconcile( String lsTranid, Connection conn )
	{
		String lsErrcode = null;
		double logAmt = 0.0;
		double logAdjAmt = 0.0;
		int liAns = 0;
		double amtAdj = 0.0;
		double lcTotamtBc = 0.0;
		double lcTotamtCurr = 0.0;
		String lsTranser = null;
		String lsTranno = null;
		int mrow1 = 0;
		//variables to be used
		String lsType = null;
		String lsBank = null;
		String lsSite = null;
		String lsRefser = null;
		String lsRefno = null;
		String lsChqno = null;
		String lsMode = null;
		String lsSundry = null;
		String lsAcct = null;
		String lsCctr = null;
		String lsStatus = null;
		String lsRemarks = null;
		String lsTranidbs = null;
		String lsKeystr = null;
		String lsCurrcode = null;
		java.sql.Timestamp ldTran = null;
		java.sql.Timestamp ldChq = null;
		java.sql.Timestamp ldToday = null;
		java.sql.Timestamp ldEff = null;
		String tranIdLog = null;
		String tranIdStat = null;
		
		String tranDateStr = null;
		
		double icAmtadj = 0.0;
		double lcAmount = 0.0;
		double lcAmtadj = 0.0;
		double lcAmtadj1 = 0.0;
		double lcAmt = 0.0;
		double lcAmt1 = 0.0;
		double lcAmtchk = 0.0;
		double lcAmtadjBc = 0.0;
		long llRows, llCnt, llCnt1 = 1;
		int liDay, liMonth, liYear;
		double lcExchrate = 0.0;
		double amount = 0.0;
		//end variables to be read
		
		String sql = null;
		PreparedStatement pStmt = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try{
			stmt = conn.createStatement( );
			sql = "select b.tran_id, b.amount, b.amt_adj, b.tran_type, b.tran_date, b.bank_code, "
				+"		b.site_code, b.tran_ser, b.tran_no, b.ref_no, b.ref_date, "
				+"		b.ref_mode, b.sundry_code, b.acct_code, b.cctr_code, "
				+"		b.remarks, b.curr_code, b.exch_rate, b.STATUS "
				+"	from banktran_log b "
				+" where tran_id = '" + lsTranid + "'";
			System.out.println( "sql :: " +  sql );
			rs = stmt.executeQuery( sql );
			if( rs.next() )
			{
				lcAmt = rs.getDouble( "amount" );
				logAmt = lcAmt;
				//lcAmount = lcAmt;
				amtAdj = rs.getDouble( "amt_adj" );
				logAdjAmt = amtAdj;
				//lcAmtadj = amtAdj;
				lsStatus = rs.getString( "status" );
				lcExchrate = rs.getDouble( "exch_rate" );
							
				//lcAmount = lcAmount - lcAmtadj;
				//lcAmt = lcAmt + lcAmount;
			
				lsType = rs.getString( "tran_type" );
				ldTran = rs.getTimestamp( "tran_date" );
		
				lsBank = rs.getString( "bank_code" );
				lsSite = rs.getString( "site_code" );
				lsRefser = rs.getString( "tran_ser" );
				lsRefno = rs.getString( "tran_no" );
				lsChqno = rs.getString( "ref_no" );

				ldChq= rs.getTimestamp( "ref_date");
				lsMode = rs.getString( "ref_mode" );
				lsSundry = rs.getString( "sundry_code" );
				lsAcct = rs.getString( "acct_code" );
				lsCctr = rs.getString( "cctr_code" );
				lsRemarks = rs.getString( "remarks" );	
			
				lsCurrcode = rs.getString( "curr_code" );
				
				lcExchrate = rs.getDouble( "exch_rate" );
			}
			
			stmt.close();
			stmt = null;
			rs.close();
			rs = null;

			if( lcExchrate == 0 )
			{
				lcExchrate = gfBankLogExchRate( lsTranser, lsTranno, conn );
			}

			if( !( "R".equalsIgnoreCase( lsStatus ) ) )
			{

				lcAmt = ( lcAmt - lcAmtadj );
				lcAmt1 = lcAmt1 + lcAmt;
				lcTotamtBc = lcAmt1 * lcExchrate;
				lcTotamtCurr = lcAmt1 / lcExchrate;
			}			
			
			if( lcExchrate == 0 )
			{
				lcExchrate = gfBankLogExchRate( lsTranser, lsTranno, conn );
			}
			lcAmount = logAmt;
			icAmtadj = logAdjAmt;
			lcAmtadj = lcAmount - icAmtadj;
			
			amtAdj = lcAmtadj;
			
			lcAmtadjBc = lcAmtadj * lcExchrate;
			lcAmtchk = lcAmtadj + icAmtadj;
			if( lcAmount == lcAmtchk )
			{
				lsStatus = "R";
				System.out.println( "In R" );
			}
			else
			{
				lsStatus = "P";
				System.out.println( "IN P" );
			}

			lcAmt = lcAmount;

			if( lsErrcode != null && lsErrcode.trim().length() > 0 )
			{
				//throw error and return
				return lsErrcode;
			}
			
			//Reconciliation process
			//lsErrcode = updateBStatBtran( headerDom, conn );
			if( lcExchrate == 0.0 )
			{
				lcExchrate = gfBankLogExchRate(lsRefser, lsRefno, conn );
			}
			lcAmtadjBc = lcAmtadj * lcExchrate;
			
			lcAmtchk = lcAmtadj + icAmtadj;
			
			System.out.println( "lcAmount::[" + lcAmount + "]lcAmtchk[" + lcAmtchk +"]" );
			if( lcAmount == lcAmtchk )
			{
				lsStatus = "R";
				System.out.println( "In R" );
			}
			else
			{
				lsStatus = "P";
				System.out.println( "IN P" );
			}

			lcAmt = lcAmount;
			
			ldToday = new java.sql.Timestamp( System.currentTimeMillis() );
			lsTranidbs = generateTranId( "W_BANK_STATEMENT", ldToday, lsSite, conn );
				
			if( lsRemarks == null ) 
				lsRemarks = "";
			
			ldEff = ldTran;
			
			String bStatIns = null;
			bStatIns = "insert into bank_statement " 
					+ " ( tran_id, bank_code, site_code, ref_no, ref_date, ref_mode, amount, " 
					+ "  tran_type, edi_ref, remarks, status, chg_date, chg_user, chg_term, "
					+ "   amt_adj, eff_date, auto_entry, status_date, exch_rate, curr_code , stat_date) "
					+ "  values ( ?, ?, ?, ?, ?, ?, ?, "
					+ "  		  ?, ' ', ?, ?, ?, ?, ?, "
					+ "  		  ?, ?, 'Y', ?, ?, ?, ? ) " ;
			System.out.println( "bStatIns :: " +  bStatIns );				
			pStmt = conn.prepareStatement( bStatIns );

			pStmt.setString( 1, lsTranidbs );
			pStmt.setString( 2, lsBank );
			pStmt.setString( 3, lsSite );
			pStmt.setString( 4, lsChqno );
			pStmt.setTimestamp( 5, ldChq );
			pStmt.setString( 6, lsMode );
			pStmt.setDouble( 7, lcAmt );
			pStmt.setString( 8, lsType );
			pStmt.setString( 9, lsRemarks );
			pStmt.setString( 10, lsStatus );
			pStmt.setTimestamp( 11, ldToday );
			pStmt.setString( 12, userid );
			pStmt.setString( 13, termid );

			pStmt.setDouble( 14, lcAmtadj );
			pStmt.setTimestamp( 15, ldEff );
			pStmt.setTimestamp( 16, ldToday );
			pStmt.setDouble( 17, lcExchrate );
			pStmt.setString( 18, lsCurrcode );
			pStmt.setTimestamp( 19, ldEff );
			
			pStmt.executeUpdate();
			
			pStmt.close();
			pStmt = null;

			if( lsErrcode != null && lsErrcode.trim().length() > 0 )
			{
				return lsErrcode;
			}
			
			lcAmt = lcAmtadj;
			
			String insBRTraceSql = null;
			insBRTraceSql = "insert into bankreco_trace ( tran_id__stat, tran_id__log, amount ) "
				+" values ( ?, ?, ?) ";
			System.out.println( "insBRTraceSql :: " +  insBRTraceSql );				
			pStmt = conn.prepareStatement( insBRTraceSql );	
			
			pStmt.setString( 1, lsTranidbs );
			pStmt.setString( 2, lsTranid );
			pStmt.setDouble( 3, lcAmt );
			
			pStmt.executeUpdate();

			pStmt.close();
			pStmt = null;
			
			lcAmtadj = lcAmtadj + icAmtadj;
			
			String updBTranLogSql = null;
			updBTranLogSql = "update banktran_log "
				+ " set status = ?, "
				+ " 	amt_adj = ?, "
				+ " 	exch_rate = ?, "
				+ " 	curr_code = ? "
				+ " where tran_id = '" + lsTranid + "'";
			System.out.println( "updBTranLogSql :: " +  updBTranLogSql );			
			pStmt = conn.prepareStatement( updBTranLogSql );
			
			System.out.println( "lsStatus :: " +  lsStatus );			
			pStmt.setString( 1, lsStatus );
			System.out.println( "lcAmtadj :: " +  lcAmtadj );			
			pStmt.setDouble( 2, lcAmtadj );
			System.out.println( "lcExchrate :: " +  lcExchrate );			
			pStmt.setDouble( 3, lcExchrate );
			System.out.println( "lsCurrcode :: " +  lsCurrcode );	
			pStmt.setString( 4, lsCurrcode );
			
			pStmt.executeUpdate();

			pStmt.close();
			pStmt = null;
			 
			//end reconciliation process

			if( lsErrcode != null && lsErrcode.trim().length() > 0 )
			{
				//throw error and return
				return lsErrcode;
			}
			//commit the transaction and close all objects
		}catch( SQLException sqlEx ){
			sqlEx.printStackTrace();
			lsErrcode = "VTRECOERR";
		}catch( Exception ex ){
			ex.printStackTrace();
			lsErrcode = "VTRECOERR";
		}finally{
			try{
				if( rs != null ){
					rs.close();
				}
				rs = null;

				if( pStmt != null ){
					pStmt.close();
				}
				pStmt = null;
				if( stmt != null ){
					stmt.close();
				}
				stmt = null;
				
			}catch( Exception et ){
			}
		}
		return lsErrcode;
	}
	private double gfBankLogExchRate( String asTranser, String asTranno, Connection conn )
	{
		String lsCurrcode = null;
		double lcExchrate = 0.0;
		String sql = null;
		Statement stmt = null;
		ResultSet rs = null;
		if( "E-PAY".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from payment_exp where tran_id = '" + asTranno.trim() + "'" ;
		}
		else if( "F-XFR".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from fundtransfer where tran_id = '" + asTranno.trim() + "'" ;
		}
		else if( "M-PAY".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from misc_payment where tran_id = '" + asTranno.trim() + "'" ;
		}else if( "M-RCP".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from misc_receipt where tran_id = '" + asTranno.trim() + "'" ;
		}else if( "MPCANC".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from misc_payment_canc where tran_id = '" + asTranno.trim() + "'" ;
		}else if( "R-DIS".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from rcpdishnr where tran_id = '" + asTranno.trim() + "'" ;
		}else if( "RCP".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from receipt where tran_id = '" + asTranno.trim() + "'" ;
		}else if( "E-FUND".equalsIgnoreCase( asTranser.trim() ) )
		{
			sql = "select curr_code, exch_rate from export_fund where tran_id = '" + asTranno.trim() + "'" ;
		}else
		{
			lsCurrcode = null;
		}
		try
		{
			stmt = conn.createStatement();
			rs = stmt.executeQuery( sql );
			if( rs.next() )
			{
				lsCurrcode = rs.getString( "curr_code" );
				lcExchrate = rs.getDouble( "exch_rate" );
			}
			rs.close();
			rs = null;
			stmt.close();
			stmt = null;
		}catch( Exception ex ){
			ex.printStackTrace();
		}
		//astr_bankdet.curr_code = ls_currcode
		//astr_bankdet.exch_rate = lc_exchrate
		return lcExchrate;
	}
	private String generateTranId( String windowName, java.util.Date tranDate, String siteCode, Connection conn )
	{
		Statement stmt = null;
		ResultSet rs = null;
		String sql = null;
		String tranId = null;
		String xmlValues = null;
		System.out.println("In Generate transId");
		System.out.println("WinName : [ " + windowName + " ]");
		System.out.println("tranDate : [ " + tranDate + " ]");
		System.out.println("siteCode : [ " + siteCode + " ]");
		 try
	     {
	    	sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE UPPER(TRAN_WINDOW)= '" + windowName + "'";
	    	System.out.println("Tran generator Sql"+sql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			System.out.println("keyString :"+rs.toString());
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);				
			}
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +	"<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues + "<tran_date>"+ tranDate + "</tran_date>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
		}
		catch (SQLException ex)
		{
			processErrString = "Exception";
			System.out.println("SQL Excep in Generate transId");
			ex.printStackTrace();
		}
		catch (Exception e)
		{
			processErrString = "Exception";
			System.out.println("Exception Generate transId" + e.getMessage());
			e.printStackTrace();
		}
		return tranId;
	}	
	public String getValidDateTimeString(String dateTimeStr, String sourceDateTimeFormat, String targetDateTimeFormat) throws ITMException
	{
		System.out.println("Getting the valid datetime string for dateTimeStr :"+dateTimeStr+": which is in format :"+sourceDateTimeFormat);
		Object date = null;
		String retDateStr = "";
		
		try
		{
			if (!(sourceDateTimeFormat.equalsIgnoreCase(targetDateTimeFormat)))
			{
				if (sourceDateTimeFormat.indexOf("/") != -1)
				{
					dateTimeStr.replace('/', '-');
				}
				else if (sourceDateTimeFormat.indexOf(".") != -1)
				{
					dateTimeStr.replace('.', '-');
				}
				date = new SimpleDateFormat(sourceDateTimeFormat).parse(dateTimeStr);
				SimpleDateFormat sdfOutput = new SimpleDateFormat(targetDateTimeFormat);
				retDateStr = sdfOutput.format(date);
			}
			else
			{
				retDateStr = dateTimeStr;
			}
		}
		catch (Exception e)
		{
			processErrString = "EXCEPTION";
			System.out.println("Excep in Generate transId");
			System.out.println("Exception :GenericUtility :getValidDateString :==>"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("retDateStr :"+retDateStr);
		return retDateStr;
	}
	//GETTING CURRENT DATE IN APPLICATION DATE FORMAT
	private String getCurrdateInAppFormat()
	{
		String currAppdate =null;
		java.sql.Timestamp currDate = null;
		Object date = null;
		SimpleDateFormat DBDate=null;
		try
		{
				
				currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
				System.out.println(genericUtility.getDBDateFormat());
			 	DBDate= new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = DBDate.parse(currDate.toString());
				currDate =	java.sql.Timestamp.valueOf(DBDate.format(date).toString() + " 00:00:00.0");
				currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
		}
		catch(Exception e)
		{
			processErrString = "EXCEPTION";
			System.out.println("Exception in  getCurrdateInAppFormat:::"+e.getMessage());
		}
		return (currAppdate);
	}	
}
