
/********************************************************
	Title : RecoveryPatternEJB
	Date  : 19/01/09
	Author: Manazir Hasan

********************************************************/

package ibase.webitm.ejb.adm;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.text.*;
import java.util.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.text.DecimalFormat;

import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class RecoveryPattern extends ProcessEJB implements RecoveryPatternLocal,RecoveryPatternRemote //SessionBean
{
	Connection sqlConn = null;
	Connection conn = null;
	String errorString = null;
	NodeList parentNodeList = null;
	NodeList childNodeList = null;
	Node parentNode = null;
	Node childNode = null;
	int ctr = 0,cnt = 0;
	String childNodeName = null;
	String errCode = "";
	int currentFormNo=0;
	int childNodeListLength;
	String selectQry = "";
	String insertQry = "";	
	String upDateQry = "";	
	String selectDtl1Qry = "";	
	String selectDtl2Qry = "";	
	String insertDtl1Qry = "";	
	String insertDtl2Qry = "";	
	String selectItem = "";	
	ResultSet rs = null;
	ResultSet detail1Rs = null;
	ResultSet detail2Rs = null;
	PreparedStatement psmt = null;
	PreparedStatement dtl1Psmt = null;
	PreparedStatement dtl2Psmt = null;
	Statement stmt = null;
	Statement dtl2Stmt = null;
	ResultSet selectRs = null;
	ResultSet dtlRs = null;
	boolean recFound = false;	
	PreparedStatement oraPsmt = null;
	Statement st = null;
	String exprNo  = null;
	String confirmed = null;
	SimpleDateFormat simpleDateFrormat  = null;
	int upd = 0;
	String procCode = "",procDateStr = "",template = "",mcCode = "",procesName = "",mcName = "",stageNo = "",procDate = "";
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	/*	
	public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called....");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/

	
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams)
		throws RemoteException,ITMException
	{
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retStr = "";
		try
		{				
			System.out.println("xmlString[process]::::::::::;;;"+xmlString);
			System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
			System.out.println("windowName[process]::::::::::;;;"+windowName);
			System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		try
		{	
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString); 
				System.out.println("headerDom" + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2); 
				System.out.println("detailDom" + detailDom);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :ImportDataPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
		}
		return retStr;
	}//END OF PROCESS (1)

	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{		
		String retStr = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "" ,sql1 = "",errString = "";
        String retString = "" ,errCode = "",tranId="";
		String loginSiteCode="",empCode="",chgUser="",chgTerm="",loginCode="";
		String 	policyNo="",insCertNo="",agent_code="",invoiceId="";
		int count =0,cnt =0;
		String curr_code="";
	    double exch_rate=0,netAmt=0;
	    Timestamp tranDate =null;
		HashMap insUpdHMap = null;		
		try
		{
			System.out.println("xtraParams :::::::::::::::::::::::::::::::::: "+xtraParams);
			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			
			
		}
	   	catch(Exception e)
		{
			   System.out.println("Exception in ImportDataPrcEJB..."+e.getMessage());
			   e.printStackTrace();
			   errString = e.getMessage();
		}
		System.out.println("returning from  ImportDataPrcEJB   "+errString);
	    return (errString);
	} //end process
	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{	
		System.out.println(">>>>>>>>>>>getData>>>>>>>>>>>>>");
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;		

		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);
			System.out.println("rtrStr.....1/20/2009......"+rtrStr); 
		}
		catch (Exception e)
		{			
			System.out.println("Exception :RecoveryPattern :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();			
		}
		return rtrStr; 
	}//END OF GETDATA(1)

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String errString=null;		
		String errCode = "";
		String getDataSql= "" ;
		String sql= "",sql1 ="" ;		
		ResultSet rs = null,rs1 = null;
		PreparedStatement pstmt = null,pstmt1 = null;		
		StringBuffer retTabSepStrBuff = new StringBuffer();		
		String saleOrderFrom ="",saleOrderTo = "",sOrderDateFrom = "",sOrderDateTo ="";
		String site_code_From ="",site_code_To = "";
		java.sql.Timestamp toDate =null;
	    java.sql.Timestamp fromDate	=null;			
		double balance = 0.00;		
		String empcode = "";
		String status = "";
		String intterm = "";		
		double instAmt = 0.00;
		int  loanTerm = 0 ;
		String ls_prd = "" ; 
		String ls_loanno = "";
		String termid = "";
		Timestamp todayDate  = null ;
		String  ls_calbase = "";
		String ls_intadd = "";
		Timestamp start = null ;
		Timestamp ld_today = null ;	
		Timestamp ld_frdate = null ;
		Timestamp ld_todate = null;		
		String ls_empcode = "";
		String ll_row = "";	
		double intperc = 0.00;
		double lc_int = 0.00; 
		int li_lineno = 0;		
		double lc_dedn =  0; 
		double lc_dedn_addl = 0.00; 
		double lc_balance_cf  =0.00; 
		String editopt = "";
		String keyfld = "";
		String  userid = "";		
		double lc_balance = 0.00;
		String  ld_todayStr = "";
		int rowno = 1;
		StringBuffer valueXmlString = new StringBuffer();
		String empCodeStr = "";
		String chgUser = "";
		String loginSiteCode = "";
		String loginCode = "";
		DecimalFormat df = new  DecimalFormat("0.00");
		ConnDriver connDriver = new ConnDriver();			
		try
		{
			ConnDriver conndriver = new ConnDriver();
			System.out.println("oracle driver found:-" + conndriver);
			conn = conndriver.getConnectDB("DriverITM");
			System.out.println("U r connected to oracle :-" + conn );
			conn.setAutoCommit(false);
			connDriver = null;
			System.out.println("xtraParams :::::::::::::::::::::::::::::::::: "+xtraParams);
			loginSiteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			empCodeStr = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
			chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			termid = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId");
			loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			// ???
			/*if (editopt.equalsIgnoreCase("A") || editopt.equalsIgnoreCase("E") )
			{
				 dw_edit.accepttext();
				ls_loanno  = dw_edit.getitemstring(1, keyfld) ;;
			}	
			else
			{*/
				//ls_loanno = dw_list.getitemstring(dw_list.getselectedrow(0), keyfld);
				ls_loanno = genericUtility.getColumnValue( "loan_no", headerDom );
				ls_loanno = ls_loanno == null ? "" : ls_loanno;
				System.out.println("see the loan_no"+ls_loanno);
			//}			
			sql =" select nvl(balance_amt,loan_amt), interest, emp_code, status, int_term, start_reco  from loans  "
				 +" where loan_no = '"+ls_loanno+"' ";
			pstmt=conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				balance =rs.getInt(1) ;
				intperc = rs.getInt(2);
				empcode = rs.getString(3) == null ? "" : rs.getString(3);
				status = rs.getString(4) == null ? "" : rs.getString(4);
				intterm = rs.getString(5) == null ? "" : rs.getString(5);
				start = rs.getTimestamp(6) ;
				
			}
			pstmt.close();
			pstmt = null;
			rs.close();
			rs= null;			
			boolean rstaus = "AU".startsWith(status);
			if ( rstaus == false)
			{	
				errCode = "VTLOAN8";
				errString =itmDBAccessEJB.getErrorString("A",errCode,chgUser);
				return (errString);				
			}				
			sql=" select count(*)  from loans_schedule where loan_no = '"+ls_loanno+"' " ;
			System.out.println("SQL FOR count(*) ==========>"+sql);
			pstmt=conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				cnt =rs.getInt(1);
			}
			pstmt.close();
			pstmt = null;
			rs.close();
			rs= null;
			System.out.println("cnt>>>>>>>>>>"+cnt);
			if(cnt==0)
			{	
				if(status.trim().equalsIgnoreCase("A"))
				{

					errCode = "VTLOAN10";
					errString =itmDBAccessEJB.getErrorString("A",errCode,chgUser);
					return (errString);
					//?? openwithparm(w_msg, 'VTLOAN10') 
					// ?? dw_reco.visible = false
					//return "" ;
				}
				else
				{
					sql ="select mon_inst, act_term  from loans where loan_no = '"+ls_loanno+"' ";
					pstmt=conn.prepareStatement(sql);
					rs = pstmt.executeQuery();
					System.out.println("SQL FOR count(*) ==========>"+sql);
					if(rs.next())
					{
						instAmt =Integer.parseInt(rs.getString(1));
						loanTerm = Integer.parseInt(rs.getString(2)) ;					
					}
					pstmt.close();
					pstmt = null;
					rs.close();
					rs= null;
					todayDate = new java.sql.Timestamp(System.currentTimeMillis()) ;									
					if(instAmt >0 || loanTerm >0 )
					{
						sql =" insert into loans_schedule (loan_no, line_no, no_inst, amount, no_inst_ded ,chg_user,chg_date,chg_term) "
							+ " VALUES ( ?, 1, NULL, ? , 0 ,?,?,'"+termid+"') ";
						pstmt=conn.prepareStatement(sql);
						pstmt.setString(1,ls_loanno);						
						pstmt.setDouble(2,instAmt);	
						pstmt.setString(3,chgUser);	
						pstmt.setTimestamp(4,todayDate);	
					}
					int insert = pstmt.executeUpdate();		
					System.out.println("insert.no of rows...."+insert);
					pstmt.close();
					pstmt = null;	
				}			
			}  // end of count
			sql ="select cal_base  from interestterm "
			 +" where int_term = '"+intterm+"' ";
			pstmt=conn.prepareStatement(sql);
			rs = pstmt.executeQuery();				
			if(rs.next())
			{
				ls_calbase = rs.getString(1) == null ? "" : rs.getString(1) ;
			
			}				
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;
			if(ls_calbase.trim().equalsIgnoreCase("E"))
			{
				ls_intadd = "Y";
			}
			else
			{
				ls_intadd = "N";
			}			
			ld_today = new java.sql.Timestamp(System.currentTimeMillis()) ;	
			ld_todayStr = ld_today.toString(); 				
			if( start.compareTo(ld_today) > 0)
			{										//if(start > ld_today)
				ld_today = start ;
			}							
			sql = " select code from period where ? between fr_date and to_date ";  
			pstmt=conn.prepareStatement(sql);
			pstmt.setTimestamp(1,ld_today);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				ls_prd  = rs.getString(1) == null ? "" : rs.getString(1) ;					
			}			
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;
			sql = " select count(*)  from payroll where prd_code = '"+ls_prd.trim()+"' and emp_code = '"+empcode.trim()+"' ";
			pstmt=conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				cnt = rs.getInt(1) ;			
			}
			pstmt.close();
			pstmt = null;
			rs.close();
			rs = null;			
			while(cnt>0)
			{
				sql = " select to_date  from period where code = '"+ls_prd +"' ";
				pstmt=conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					ld_todate = rs.getTimestamp(1) ;
										
				}
				System.out.println("sql>>>>>>>>"+sql);
				System.out.println("ld_todate>>>>>>>>"+ld_todate);
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
				long totsecs = ld_todate.getTime();
				ld_frdate = new Timestamp(totsecs+24*60*60);				
				sql = "select code  from period where fr_date = '"+ld_frdate+"' ";
				pstmt = conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					ls_prd = rs.getString(1) == null ? "" : rs.getString(1)  ;
				
				}				
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
				sql = " select count(*)  from payroll where prd_code = '"+ls_prd+"' and emp_code = '"+empcode+"' ";
				pstmt=conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					cnt = rs.getInt(1) ;
				
				}				
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;				
			}
			while(balance > 0 )
			{								
				valueXmlString.append(rowno++).append("\t");
				valueXmlString.append(ls_prd.trim()).append("\t");
				valueXmlString.append(df.format(balance)).append("\t");
				//valueXmlString.append(ls_intadd.trim()).append("\t");										
				if (intperc!=0) 
				{
					lc_int = balance * (intperc/100)/12 ;
				}							

				valueXmlString.append(df.format(lc_int)).append("\t");
				// added extra on 1/21/2009 computed field in ITM
				if (ls_intadd .trim().equalsIgnoreCase("Y")) 
				{
					valueXmlString.append(df.format(balance + lc_int)).append("\t");
				}
				else
				{
					valueXmlString.append(df.format(balance)).append("\t");
				}

				// end of computed logic 

				sql = " select min(line_no)   from loans_schedule   where loan_no = '"+ls_loanno+"' "
						+"	and (no_inst <> no_inst_ded or (no_inst is null and prd_code is null)) ";
				pstmt=conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					li_lineno = rs.getInt(1) ;
				
				}				
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;
				sql = "select amount  from loans_schedule  where loan_no = '"+ls_loanno+"'  and line_no = '"+li_lineno+"' ";
				pstmt=conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					lc_dedn  = rs.getInt(1) ;
				
				}				
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;	
				sql = "update loans_schedule set no_inst_ded = (no_inst_ded + 1) where loan_no = '"+ls_loanno+"' and line_no = '"+li_lineno+"' " ;
				pstmt=conn.prepareStatement(sql);					
				int updaterow = pstmt.executeUpdate();					
				pstmt.close();
				pstmt = null;		
				if (ls_intadd.trim().equalsIgnoreCase("Y"))
				{
					if(lc_dedn > (balance + lc_int)) 
						{ 
							lc_dedn =balance + lc_int ;
						}
				}
				else
				{
					if (lc_dedn > balance)
						{
							lc_dedn = balance ;
						}
				}				
				valueXmlString.append(df.format(lc_dedn)).append("\t");
				lc_dedn_addl = 0 ;					
				sql = " select amount  from loans_schedule where loan_no = '"+ls_loanno+"' and prd_code = '"+ls_prd+"'  ";
				pstmt=conn.prepareStatement(sql);
				rs = pstmt.executeQuery();					
				if(rs.next())
				{
					lc_dedn_addl  = rs.getInt(1) ;					
				}			
				pstmt.close();
				pstmt = null;
				rs.close();
				rs = null;				
				valueXmlString.append(df.format(lc_dedn_addl)).append("\t");				
				// added  on 1/21/2009  computed filed 
					valueXmlString.append(df.format(lc_dedn + lc_dedn_addl)).append("\t");
				// end of computed logic

				if (ls_intadd .trim().equalsIgnoreCase("Y")) 
				{
					lc_balance_cf = balance + lc_int - lc_dedn - lc_dedn_addl ;
				}	
				else
				{
					lc_balance_cf = balance - lc_dedn - lc_dedn_addl ;
				}
					
				if (lc_balance_cf < 0)
				{
					 lc_balance_cf = 0 ;
				} 				
				valueXmlString.append(df.format(lc_balance_cf)).append("\t");	
				balance = lc_balance_cf ;				
				String prd = "";
				prd = ls_prd.substring(4,6);			
				if(prd.equalsIgnoreCase("12"))
				{
					ls_prd = String.valueOf((Long.parseLong(ls_prd.substring(0,4)) + 1) + "01");
				}	
				else	
				{
					ls_prd = String.valueOf(Long.parseLong(ls_prd) + 1);
				}				
				
				valueXmlString.append("\n");
			} 		
			// end of code	
			conn.rollback();			
			//System.out.println("valueXmlString..." + valueXmlString);				
			
		}
		catch(Exception e)
		{							
				e.printStackTrace();			
				System.out.println("Exception ::" + e.getMessage());
				throw new ITMException(e);
			
		}
		finally
		{
			try
			{
				retTabSepStrBuff = null;
				conn.rollback();
				if(conn != null)
				{					
					if(pstmt != null)
					{
						pstmt.close();
						pstmt=null;
					}
					conn.close();
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return valueXmlString.toString();	
	}//END OF GETDATA(2)
	
	// fuctions for transfering data
	 
}