package ibase.webitm.ejb.adm;

import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.ejb.*;
import ibase.system.config.*;
import ibase.utility.*;

import java.util.*;
import java.util.Date;
import java.sql.*;
import java.io.*;

import java.rmi.RemoteException;
import javax.ejb.*;
import javax.naming.InitialContext;
import java.text.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;

@Stateless
public class  MiscRcpLoanAdjPrc extends ProcessEJB implements MiscRcpLoanAdjPrcLocal,MiscRcpLoanAdjPrcRemote 
{
	SessionContext cSessionContext;
	
	String  userId= "";
	public void setSessionContext(SessionContext mSessionContext) 
	{
		try
		{
			CommonConstants.setIBASEHOME();
			ProcessEJB.DB_NAME = CommonConstants.DB_NAME;
			this.cSessionContext = mSessionContext;
		}
		catch (Exception e)
		{
			System.out.println("Exception :MiscRcpLoanAdjPrc :setSessionContext :==>"+e);
			e.printStackTrace();
			System.out.println("Inside [MiscRcpLoanAdjPrc][setSessionContext]>>"+e.toString());
		}
	}
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		System.out.println("Inside [MiscRcpLoanAdjPrc] <<getData()>>");
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("getData xmlString =["+xmlString+"]");
			System.out.println("getData xmlString2 =["+xmlString2+"]");
			System.out.println("getData xtraParams =["+xtraParams+"]");
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :MiscRcpLoanAdjPrc :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			System.out.println("Inside [MiscRcpLoanAdjPrc][getData]>>"+e.toString());
		}
		return rtrStr; 
	}
	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("Inside [MiscRcpLoanAdjPrc][getData(Document headerDom, Document detailDom, String windowName, String xtraParams)]>>" );
		
		String empCode = "";
		String loanNo ="" ;
		String schmNo ="";
		String schmDescr ="";
		String balAmt  = "";
		Date StartRecDate =null;
		String StartRec  = "";
		String loanAmt ="";
		String recoAmt = "";
		String errCode = "";
		String errString = "";
		String siteCode= "" ;
		String sql= "" ;
		String resultString = "";
		String userId ="";
		String tranSer ="";
		String refNo ="";
		Connection conn = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		boolean isPendingLoanFound = false;
		double payableBalance = 0d;
		double adjAmt = 0d;
		double loanBalAmt = 0d;
	
		StringBuffer retTabSepStrBuff = new StringBuffer("<?xml version=\"1.0\"?>\r\n<DocumentRoot>\r\n<description>Datawindow Root</description>\r\n<group0>\r\n<description>Group0 description</description>\r\n<Header0>\r\n<description>Header0 members</description>\r\n");
	
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		
		try
		{
			empCode = genericUtility.getColumnValue("emp_code",detailDom);
			tranSer = genericUtility.getColumnValue("tran_ser",detailDom);
			refNo = genericUtility.getColumnValue("ref_no",detailDom);
			System.out.println("empCode ---->"+empCode);
			
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext ctx = new InitialContext(appConnect.getProperty()) ;
			ITMDBAccessLocal itmDBAccessEJB = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");		
			
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");

			sql = "SELECT CASE WHEN TOT_AMT IS NULL THEN 0 ELSE TOT_AMT END - " + 
					" CASE WHEN ADJ_AMT IS NULL THEN 0 ELSE ADJ_AMT END AS BALANCE_AMT " + 
					" FROM MISC_PAYABLES WHERE TRAN_SER = ? AND REF_NO = ?" ;
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,checkNull(tranSer));
			pstmt.setString(2,checkNull(refNo));
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				payableBalance = rs.getDouble("BALANCE_AMT");
			}
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			if (payableBalance > 0d)
			{
				sql =	 "  SELECT LOANS.LOAN_NO,  "+ 
								" LOANS.SCHEME_NO,  "+
								" LOAN_SCHEME.DESCR, "+ 
								" LOANS.BALANCE_AMT,  "+ 
								" LOANS.START_RECO,  "+ 
								" LOANS.LOAN_AMT,   "+
								" 0.00 AS RECO_AMT  "+
						   " FROM LOANS,   "+
								"  LOAN_SCHEME  "+
						   " WHERE ( LOAN_SCHEME.SCHEME_NO = LOANS.SCHEME_NO ) AND  "+
								"  ( LOANS.EMP_CODE = ? ) AND  "+
								"  ( LOANS.STATUS = 'A' ) AND  "+
								"  ( LOANS.START_DEDN = 'Y') AND  "+
								"  ( LOANS.BALANCE_AMT > 0 )   "  ;
			
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,checkNull(empCode));
				rs = pstmt.executeQuery();
				int i = 0;
				while(rs.next())
				{
					loanNo 	=  	checkNull(rs.getString("LOAN_NO"));
					
					schmNo 		=   checkNull(rs.getString("SCHEME_NO"));
					System.out.println("loanNo ---->"+loanNo);
					
					schmDescr 	=   checkNull(rs.getString("DESCR"));
					System.out.println("schmDescr ---->"+schmDescr);
			  	
					balAmt		=   rs.getString("BALANCE_AMT");
					loanBalAmt		=   rs.getDouble("BALANCE_AMT");

					System.out.println("balAmt ---->"+balAmt);
					adjAmt = 0d;
					if (loanBalAmt >= payableBalance && payableBalance > 0d)
					{
						adjAmt = payableBalance;
						payableBalance = 0d;
					}
					else 
					{
						if (payableBalance > 0d)
						{
							adjAmt = loanBalAmt;
							payableBalance = payableBalance - loanBalAmt;
						}
					}

					StartRecDate	=	rs.getDate("START_RECO");
					System.out.println("StartRec ---->"+StartRecDate);
					if(StartRecDate==null)
					{
						StartRec = "";
					}else
					{
						StartRec=simpleDateFormat.format(StartRecDate) ;
					}
					
					loanAmt		=	rs.getString("LOAN_AMT");
					System.out.println("loanAmt ---->"+loanAmt);
					
					recoAmt 	=	rs.getString("RECO_AMT");
					recoAmt = "" + adjAmt;
					System.out.println("recoAmt ---->"+recoAmt);
					
					
					retTabSepStrBuff.append("<Detail2 dbID='"+loanNo+"' domID='"+i+"' >\r\n");
					retTabSepStrBuff.append("<attribute updateFlag='N' selected='N' />\r\n");

					retTabSepStrBuff.append("<scheme_descr><![CDATA[").append(schmDescr).append("]]></scheme_descr>\r\n");
					retTabSepStrBuff.append("<start_reco><![CDATA[").append(StartRec).append("]]></start_reco>\r\n");
					retTabSepStrBuff.append("<balance_amt><![CDATA[").append(balAmt).append("]]></balance_amt>\r\n");
					retTabSepStrBuff.append("<reco_amt><![CDATA[").append(recoAmt).append("]]></reco_amt>\r\n");
					retTabSepStrBuff.append("<loan_amt><![CDATA[").append(loanAmt).append("]]></loan_amt>\r\n");
					retTabSepStrBuff.append("<loan_no><![CDATA[").append(loanNo).append("]]></loan_no>\r\n");
					retTabSepStrBuff.append("<scheme_no><![CDATA[").append(schmNo).append("]]></scheme_no>\r\n");
					
					retTabSepStrBuff.append("</Detail2>\r\n");   
					
					i++;
					isPendingLoanFound = true;
				}

				retTabSepStrBuff.append("</Header0></group0></DocumentRoot>");

				if (isPendingLoanFound)
				{
					resultString = retTabSepStrBuff.toString();
				}
				else
				{
					resultString = itmDBAccessEJB.getErrorString("" , "VTLOAN13" , "" , "" , conn);
				}
			}
			else
			{
				resultString = itmDBAccessEJB.getErrorString("" , "VTLOAN12" , "" , "" , conn);
			}

		}
		catch(Exception e)
		{
			e.printStackTrace();
				
		}
		finally
		{
			try
			{
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if (conn != null)
				{
					conn.close();
					conn = null;
				}		
			}
			catch(Exception e)
			{
				e.printStackTrace();
			
			}
		}

		System.out.println("ResultString....." + resultString);
			
		return resultString;
	}
	private String checkNull(String input)
	{
		if (input==null)
		{
			input="";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
}
