/* This EJB is Cteated it incorporate the Pre Save logic from ue_save Of Window(w_emp_Ad)
 * Gulzar 15/01/07
 */

package ibase.webitm.ejb.adm;
import java.rmi.RemoteException;

import java.sql.*;
import javax.ejb.*;
import org.w3c.dom.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class EmpAdPrs extends ValidatorEJB implements EmpAdPrsLocal,EmpAdPrsRemote	// SessionBean
{
	/*
	public void ejbCreate() throws RemoteException, CreateException 
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate() 
	{
	}

	public void ejbPassivate() 
	{
	}*/
    public String preSaveRec() throws RemoteException,ITMException
	{
		return "";
	}
	
	public String preSaveRec(String xmlString1,String domId,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		System.out.println("EmpAdPrsEJB called...........");
		String retString = "";
		Document dom = null;
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				retString = executepreSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}			
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :EmpAdPrsEJB :preSaveRec() :" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retString;
	}

	private String executepreSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String empCode = "", adCode = "", effDate = "", expDate = "", periodFrom = "", periodTo = "";
		String sqlStr = "", amt = "", keyString = "", errorCode = "";
		String updateStatus = "", userId = "", retString = "";
		double originalAmt = 0d, amount = 0d;
		boolean empStatus = false;
		int count = 0;
		java.sql.Timestamp effectiveDate = null, expiryDate = null;
		Node currDetail = null;
		try
		{
			conn.setAutoCommit(false);
			GenericUtility genericUtility = GenericUtility.getInstance();
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
			AdmCommon admCommon = new AdmCommon();
			System.out.println("dom.............:: "+ dom);
			System.out.println("domID.............:: "+ domID);
			currDetail 	= getCurrentDetailFromDom(dom,domID);
			updateStatus = getCurrentUpdateFlag(currDetail);
			System.out.println("updateStatus......:: "+ updateStatus);
			if (currDetail != null)
			{
				if(updateStatus.equalsIgnoreCase("A") || updateStatus.equalsIgnoreCase("E"))
				{
					if(updateStatus.equals("A"))
					{
						empCode = genericUtility.getColumnValueFromNode("emp_code",currDetail);
						adCode	= genericUtility.getColumnValueFromNode("ad_code",currDetail);
						effDate = genericUtility.getColumnValueFromNode("eff_date",currDetail);
						empStatus = admCommon.empPrevRec(empCode, adCode, effDate, conn);
					}
					if(empStatus)
					{
						expDate = genericUtility.getColumnValueFromNode("exp_date",currDetail);
						amt	= genericUtility.getColumnValueFromNode("amount",currDetail);
						if (amt != null)
						{
							amount = Double.parseDouble(amt);
						}
						effectiveDate	= java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(effDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
						expiryDate		= java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(expDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
						System.out.println("effectiveDate...:: " + effectiveDate);
						System.out.println("expiryDate...:: " + expiryDate);
						sqlStr = "SELECT CODE FROM PERIOD WHERE FR_DATE <= ? AND TO_DATE >= ? " ;
						System.out.println("sqlStr.....::[1]:: " + sqlStr);
						pstmt = conn.prepareStatement(sqlStr);
						pstmt.setTimestamp(1,effectiveDate);
						pstmt.setTimestamp(2,effectiveDate);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							periodFrom = rs.getString("CODE");
						}
						System.out.println("periodFrom:: " + periodFrom);
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						sqlStr = "SELECT CODE FROM PERIOD WHERE FR_DATE <= ? AND TO_DATE >= ? " ;
						System.out.println("sqlStr.....::[2]:: " + sqlStr);
						pstmt = conn.prepareStatement(sqlStr);
						pstmt.setTimestamp(1,expiryDate);
						pstmt.setTimestamp(2,expiryDate);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							periodTo = rs.getString("CODE");
						}
						System.out.println("periodTo:: " + periodTo);
						rs.close();
						rs = null;
						keyString = empCode + "|" + adCode + "|" + effectiveDate + "|" + expiryDate;
						sqlStr = "SELECT BASIC FROM EMPLOYEE WHERE EMP_CODE = '"+empCode+"'" ;
						System.out.println("sqlStr.....::[3]:: " + sqlStr);
						stmt = conn.createStatement();
						rs = stmt.executeQuery(sqlStr);
						if (rs.next())
						{
							originalAmt = rs.getDouble("BASIC");
						}
						rs.close();
						rs = null;
						errorCode = admCommon.payarrToProcUpdation(periodFrom, periodTo, empCode, empCode, "AR", "W_EMP_AD", keyString, adCode, amount - originalAmt, effDate, expDate, xtraParams, conn);
						if (errorCode.trim().length() > 0)
						{
							conn.rollback();
							retString = getErrorString("",errorCode,userId);
							System.out.println("Ret String: " + retString);
						}
						else if (errorCode.trim().length() == 0)
						{
							conn.commit();
						}
					}//End Of if(empStatus)
				}
				else if (updateStatus.equalsIgnoreCase("D"))
				{
					empCode = genericUtility.getColumnValueFromNode("emp_code",currDetail);
					adCode	= genericUtility.getColumnValueFromNode("ad_code",currDetail);

					sqlStr = "SELECT COUNT(*) AS COUNT FROM PAYROLLDET WHERE EMP_CODE = '"+empCode+"' and ad_code = '"+adCode+"'";
					System.out.println("sqlStr.........:: " + sqlStr);
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sqlStr);
					if (rs.next())
					{
						count = rs.getInt("COUNT");
					}
					if (count != 0)
					{
						errorCode = "VTPAYFND";
						retString = getErrorString("",errorCode,userId);
						System.out.println("Ret String: " + retString);
					}
				}
			}//End Of if(currDetail)
		}//End Of Try Block
		catch (SQLException sqe)
		{
			System.out.println("The SQLException occurs in [EmpAdPrsEJB] :: [executepreSaveRec] :"+sqe);
			sqe.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception sqe1){}
			throw new ITMException(sqe);
		}
		catch(Exception e)
		{
			System.out.println("The Exception occurs in [EmpAdPrsEJB] :: [executepreSaveRec] :"+e);			
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing stmt and pstmt In [executepreSaveRec]......");
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :[EmpAdPrsEJB] :: [executepreSaveRec] :\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return retString;
	}
	private Node getCurrentDetailFromDom(Document dom,String domId)
	{
		NodeList detailList = null;
		Node currDetail = null,reqDetail = null;
		String currDomId = "";
		int	detailListLength = 0;

		detailList = dom.getElementsByTagName("Detail1");
		detailListLength = detailList.getLength();
		for (int ctr = 0;ctr < detailListLength;ctr++)
		{
			currDetail = detailList.item(ctr);
			currDomId = currDetail.getAttributes().getNamedItem("domID").getNodeValue();
			if (currDomId.equals(domId))
			{
				reqDetail = currDetail;
				break;
			}			
		}
		return reqDetail;
	}

	private String getCurrentUpdateFlag(Node currDetail)
	{
		NodeList currDetailList = null;
		String updateStatus = "",nodeName = "";
		int currDetailListLength = 0;

		currDetailList = currDetail.getChildNodes();
		currDetailListLength = currDetailList.getLength();
		for (int i=0;i< currDetailListLength;i++)
		{
			nodeName = currDetailList.item(i).getNodeName();
			if (nodeName.equalsIgnoreCase("Attribute"))
			{
				updateStatus = currDetailList.item(i).getAttributes().getNamedItem("updateFlag").getNodeValue();
				break;
			}
		}
		return updateStatus;		
	}	
}