package ibase.webitm.ejb.adm.adv;

import java.rmi.RemoteException;
import java.util.*;
import java.sql.*;
import javax.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import javax.ejb.Stateless; // added for ejb3
// 05/05/10 manoharan
import java.text.SimpleDateFormat;
// end 05/05/10 manoharan
@Stateless // added for ejb3

public class LoanscheduleStDedn extends ActionHandlerEJB implements LoanscheduleStDednLocal,LoanscheduleStDednRemote //SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate() 
	{
	}

	public void ejbPassivate() 
	{
	}*/

    public String actionHandler() throws RemoteException,ITMException
	{
		return "";
	}
	
	public String actionHandler(String tranID, String xtraParams, String forcedFlag) throws RemoteException,ITMException
	{
		System.out.println("LoanscheduleStDednEJB is called");
		String  retString = null;
		try
		{
			retString = actionStartDedn(tranID,xtraParams);
			System.out.println("retString  :"+retString);
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :actionHandler:" + e.getMessage() + ":");
			throw new ITMException(e);
		}
	    return retString;
	}

	private String actionStartDedn(String tranId ,String xtraParams)throws SQLException,Exception
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;	
		ResultSet rs = null;
		String sql = "", loginEmpCode  = "", start = "", status = "", errString = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		String winName = "w_start_dedn_load", errCode  = "";
		try
		{	
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			loginEmpCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			System.out.println("TranId ::"+tranId);
			sql = "SELECT START_DEDN, STATUS FROM LOANS WHERE LOAN_NO = '"+tranId+"'";
			System.out.println("sql ::"+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				start = rs.getString(1);
				status = rs.getString(2);
			}
			System.out.println("start ::"+start+" status :"+status);
			if (start == null || start.equals(""))
			{
				start = "N";
			}	
			if (start.equals("N") && status.equals("A"))
			{
				if (loginEmpCode == null || loginEmpCode.trim().length() == 0)
				{
					errCode = "EMPAPRV";
				}
				else
				{
					errCode = startDedn(conn, tranId, xtraParams);
				}
			}
			else
			{
				errCode = "VTLOANS1";
			}
			if (errCode != null && errCode.trim().length() > 0) 
			{
				conn.rollback();
				errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);				
			}
			else
			{
				conn.commit();
				errString = itmDBAccessEJB.getErrorString("","VTLOANS2","","",conn);				
			}
		}
		catch(SQLException sqx)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + sqx.getMessage() + ":");
			throw sqx;
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + e.getMessage() + ":");
			throw e;
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection.....");
				conn.close();
				conn = null;
			}catch(Exception e){}
		}
		return errString;
	}

	private String startDedn(Connection conn, String loanNo, String xtraParams) throws SQLException,Exception
	{
		System.out.println("Calling startDedn().....");
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;	
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();
		String dateInterest = "", errCode = "";
		String sql = "", empCode = "", period = "", retDate1 = "";
		java.util.Date toDate = null, retDate = null, frDate = null, startReco = null, issueDate2 = null;
		java.sql.Date issueDate = null;
		int count  = 0, updateCnt = 0;
		// 21/07/10 manoharan to remove the milliseconds
		SimpleDateFormat simpleDateFormat = null;
		String dateFromString = null;
		java.sql.Timestamp iDT = null;
		// end 21/07/10 manoharan to remove the milliseconds
		
		try
		{
			simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			stmt = conn.createStatement();
			sql = "SELECT DATE__INTEREST, ISSUE_DATE, EMP_CODE FROM LOANS "
			     +"WHERE LOAN_NO = '"+loanNo+"'";
			System.out.println("sql :"+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				dateInterest = rs.getString(1);
				issueDate = rs.getDate(2);
				empCode = rs.getString(3);
			}
			System.out.println("dateInterest  :"+dateInterest+" issueDate :"+issueDate+" empCode :"+empCode);
			if (dateInterest == null || dateInterest.trim().length() == 0)
			{
				sql = "SELECT CODE, FR_DATE, TO_DATE FROM PERIOD "
				     +"WHERE ? BETWEEN FR_DATE AND TO_DATE";
				System.out.println("sql :"+sql);
				pstmt = conn.prepareStatement(sql);
				// 21/07/10 manoharan to remove the milliseconds
				
				dateFromString = simpleDateFormat.format(issueDate);
				iDT = java.sql.Timestamp.valueOf(dateFromString + " 00:00:00");
				//pstmt.setTimestamp(1,new java.sql.Timestamp(issueDate.getTime()));
				pstmt.setTimestamp(1,iDT);
				// end 21/07/10 manoharan to remove the milliseconds

				rs = pstmt.executeQuery();
				if (rs.next())
				{
					period = rs.getString(1);
					frDate = rs.getDate(2);
					toDate = rs.getDate(3);
				}
				System.out.println("period :"+period+" frDate :"+frDate+" toDate :"+toDate);
				sql = "SELECT COUNT(*) FROM PAYROLL WHERE PRD_CODE = '"+period+"' " 
					 +"AND EMP_CODE = '"+empCode+"'";;
				System.out.println("sql :"+sql);
				rs = stmt.executeQuery(sql);
				if (rs.next())
				{
					count = rs.getInt(1);
				}
				System.out.println("count :"+count);
				while (count > 0)
				{
					Calendar  cal = Calendar.getInstance();
					cal.setTime(toDate); // date
					cal.add(Calendar.DATE,1);//days
					frDate = cal.getTime();
					System.out.println("frDate  :"+frDate); 
					sql = "SELECT CODE , TO_DATE FROM PERIOD WHERE FR_DATE = ?";
					pstmt = conn.prepareStatement(sql);
					// 21/07/10 manoharan
					dateFromString = simpleDateFormat.format(frDate);
					//pstmt.setTimestamp(1,new java.sql.Timestamp(frDate.getTime()));
					pstmt.setTimestamp(1,java.sql.Timestamp.valueOf(dateFromString + " 00:00:00"));
					// end 21/07/10 manoharan
					rs = pstmt.executeQuery();
					if (rs.next())
					{
						period = rs.getString(1);
						toDate = rs.getDate(2);
					}
					sql = "SELECT COUNT(*) FROM PAYROLL "
				         +"WHERE PRD_CODE = '"+period+"'"+" AND EMP_CODE = '"+empCode+"'";
					System.out.println("sql :"+sql);
					rs = stmt.executeQuery(sql);
					if (rs.next())
					{
						count = rs.getInt(1);
					}
					System.out.println("count :"+count);
				}
				sql = "SELECT START_RECO FROM LOANS WHERE LOAN_NO ='"+loanNo+"'";
				System.out.println("sql :"+sql);
				rs = stmt.executeQuery(sql);
				if (rs.next())
				{
					startReco = rs.getDate(1);
				}
				if (startReco.compareTo(frDate) <= 0)
				{
					sql = "UPDATE LOANS SET START_RECO = ? " 
				         +"WHERE LOAN_NO = '"+loanNo+"'";
					System.out.println("sql :"+sql);
					pstmt = conn.prepareStatement(sql);
					// 21/07/10 manoharan milliseconds are set to be avoided
					dateFromString = simpleDateFormat.format(frDate);
					java.sql.Timestamp startRecoDate =  java.sql.Timestamp.valueOf(dateFromString + " 00:00:00.000");
					//pstmt.setTimestamp(1,new java.sql.Timestamp(frDate.getTime()));
					pstmt.setTimestamp(1,startRecoDate);
					// end 21/07/10 manoharan
					updateCnt = pstmt.executeUpdate();
					System.out.println("No. of Records updated ::"+updateCnt);
					if (updateCnt > 0)
					{
						errCode = CreateInst(conn, loanNo, xtraParams);
						System.out.println("errCode  :"+errCode);
						if (errCode == null || errCode.trim().length() == 0)
						{
							sql = "UPDATE LOANS SET DATE__INTEREST = ?, START_DEDN = ? "
							 +"WHERE LOAN_NO = ?";
							System.out.println("sql :"+sql);
							pstmt = conn.prepareStatement(sql);
							// 21/17/10 manoharan milliseconds are set to be avoided
							//pstmt.setTimestamp(1,new java.sql.Timestamp(issueDate.getTime()));
							pstmt.setTimestamp(1,iDT);
							// end 21/07/10 manoharan milliseconds are set to be avoided
							pstmt.setString(2,"Y");
							pstmt.setString(3,loanNo);
							updateCnt = pstmt.executeUpdate();
							System.out.println("No. of Records updated ::"+updateCnt);				
							if (updateCnt == 0)
							{
								errCode = "DS000NR";
							}				
						}						
					}
					else
					{
						errCode = "DS000NR";
					}
				}								
			}//end if
		}//try end
		catch(SQLException sqx)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + sqx.getMessage() + ":");
			throw sqx;
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + e.getMessage() + ":");
			throw e;
		}
		finally
		{
			try
			{
				if (stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}catch(Exception e){}
		}
		return errCode;
	}

	private String CreateInst(Connection conn, String loanNo, String xtraParams) throws SQLException,Exception
	{
		System.out.println("Calling CreateInst().....");
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;	
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		String empCode = "", schemeNo = "", adCodeDed = "", errCode = "", sql = "";
		double loanAmt = 0, monInst = 0;
		int term = 0, count = 0, insertCnt = 0;
		java.sql.Date reqDate = null, startReco = null, dateLd = null;
		SimpleDateFormat simpleDateFormat = null;
		String dateFromString = null;
		// end 21/07/10 manoharan to remove the milliseconds
		
		try
		{
			simpleDateFormat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			stmt = conn.createStatement();
			sql = "SELECT START_RECO, EMP_CODE, LOAN_AMT, MON_INST, TERM, SCHEME_NO "
				 +"FROM LOANS WHERE LOAN_NO = '"+loanNo+"'";
			System.out.println("sql :"+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				startReco = rs.getDate(1);
				empCode = rs.getString(2);
				loanAmt = rs.getDouble(3);
				monInst = rs.getDouble(4);
				term = rs.getInt(5);
				schemeNo = rs.getString(6);
			}
			System.out.println("startReco :"+startReco+" empCode :"+empCode+" loanAmt :"+loanAmt);	
			System.out.println("monInst :"+monInst+" term :"+term+" schemeNo :"+schemeNo);	

			sql = "SELECT AD_CODE__DED FROM LOAN_SCHEME WHERE SCHEME_NO = '"+schemeNo+"'";
			System.out.println("sql :"+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				adCodeDed = rs.getString(1);
			}
			System.out.println("adCodeDed :"+adCodeDed);
			if (term > 1)
			{
				term = term-1;
				reqDate = addMonth(startReco, term);
				reqDate = lastDate(reqDate);
			}
			else
			{
				reqDate = lastDate(startReco);
			}
			dateLd = reqDate;
			sql = "SELECT COUNT(*) FROM ALLOWDEDN_BAL  "
				 +"WHERE EMP_CODE = ? " 
				 +"AND AD_CODE = ? "
				 +"AND START_DATE = ?"
				 +"AND END_DATE = ?";
			System.out.println("sql :"+sql);
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1,empCode);
			pstmt.setString(2,adCodeDed);
			// 21/07/10 manoharan
			dateFromString = simpleDateFormat.format(startReco);
			//pstmt.setTimestamp(3,new java.sql.Timestamp(startReco.getTime()));
			pstmt.setTimestamp(3,java.sql.Timestamp.valueOf(dateFromString + " 00:00:00.000"));
			dateFromString = simpleDateFormat.format(dateLd);
			//pstmt.setTimestamp(4,new java.sql.Timestamp(dateLd.getTime()));
			pstmt.setTimestamp(4,java.sql.Timestamp.valueOf(dateFromString + " 00:00:00.000"));
			// end 21/07/10 manoharan
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				count = rs.getInt(1);
			}
			System.out.println("count :"+count);
			if (count == 0)
			{
				sql = "INSERT INTO ALLOWDEDN_BAL ( "
					 +"EMP_CODE, "
					 +"AD_CODE, "
					 +"START_DATE, "
					 +"END_DATE, "
					 +"AMOUNT, "
				     +"AMT_ADJ, "
					 +"AMT_BAL, "
					 +"CHG_DATE, "
					 +"CHG_USER, "
					 +"CHG_TERM, "
					 +"REF_TYPE, "
					 +"REF_NO) " 
			         +"VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
				System.out.println("sql :"+sql);
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,empCode);
				pstmt.setString(2,adCodeDed);
				// 21/07/10 manoharan
				dateFromString = simpleDateFormat.format(startReco);
				//pstmt.setTimestamp(3,new java.sql.Timestamp(startReco.getTime()));
				pstmt.setTimestamp(3,java.sql.Timestamp.valueOf(dateFromString + " 00:00:00.000"));
				dateFromString = simpleDateFormat.format(dateLd);
				//pstmt.setTimestamp(4,new java.sql.Timestamp(dateLd.getTime()));
				pstmt.setTimestamp(4,java.sql.Timestamp.valueOf(dateFromString + " 00:00:00.000"));
				pstmt.setDouble(5,loanAmt);
				pstmt.setInt(6,0);
				pstmt.setDouble(7,loanAmt);
				pstmt.setTimestamp(8,new java.sql.Timestamp(System.currentTimeMillis()));
				pstmt.setString(9,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode"));
				pstmt.setString(10,genericUtility.getValueFromXTRA_PARAMS(xtraParams,"termId"));
				pstmt.setString(11,"L");
				pstmt.setString(12,loanNo);
				insertCnt = pstmt.executeUpdate();
				System.out.println("insertCnt  :"+insertCnt);
			}
			else
			{
				errCode = "VTLNFND";
			}
		}
		catch(SQLException sqx)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + sqx.getMessage() + ":");
			throw sqx;
		}
		catch(Exception e)
		{
			System.out.println("Exception :LoanscheduleStDednEJB :" + e.getMessage() + ":");
			throw e;
		}
		finally
		{
			try
			{
				if (stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}catch(Exception e){}
		}
		return errCode;
	}

	private java.sql.Date addMonth(java.sql.Date startReco, int term) throws Exception
	{
		java.util.Date start = null, retDateUtil = null;
		java.sql.Date retDate = null;
		try
		{
			start = new java.util.Date(startReco.getTime());
			Calendar  cal = Calendar.getInstance();			
			cal.setTime(start);
			cal.add(Calendar.MONTH,term);
			retDateUtil = cal.getTime();
			System.out.println("retDateUtil from addMonth():"+retDateUtil);
			retDate = new java.sql.Date(retDateUtil.getTime());
		}
		catch (Exception e)
		{
			System.out.println("Exception :LoanScheduleStDednEJB(addMonth())"+e);
			throw e;
		}
		return retDate;
	}

	private java.sql.Date lastDate(java.sql.Date startReco) throws Exception
	{
		java.util.Date start = null, retDateUtil = null;
		java.sql.Date retDate = null;
		try
		{
			start = new java.util.Date(startReco.getTime());
			Calendar  cal = Calendar.getInstance();			
			cal.setTime(start);
			cal.add(Calendar.MONTH,1);
			cal.set(Calendar.DATE,0);
			retDateUtil = cal.getTime();
			System.out.println("retDateUtil from lastDate() :"+retDateUtil);
			retDate = new java.sql.Date(retDateUtil.getTime());
		}
		catch (Exception e)
		{
			System.out.println("Exception :LoanScheduleStDednEJB(lastDate())"+e);
			throw e;
		}
		return retDate;
	}
	
	
}