/* 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 EmpMthadPrs extends ValidatorEJB implements EmpMthadPrsLocal,EmpMthadPrsRemote // 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("EmpMthadPrsEJB called...........");
		Document dom = null;
		try
		{
			if (xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString1);
				executepreSaveRec(dom,domId,objContext,editFlag,xtraParams,conn);
			}			
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :EmpMthadPrsEJB :preSaveRec() :" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return "";
	}

	private String executepreSaveRec(Document dom, String domID,String objContext,String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		PreparedStatement pstmt = null;
		Statement stmt = null;
		ResultSet rs = null;
		String empCode = "", adCode = "", effDate = "", expDate = "", periodFrom = "", periodTo = "";
		String sqlStr = "", amt = "", keyString = "", errorCode = "", monthCode = "";
		String updateStatus = "", userId = "", retString = "";
		double originalAmt = 0d, amount = 0d;
		boolean empStatus = false;
		java.sql.Timestamp effectiveDate = null, expiryDate = null;
		Node currDetail = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		try
		{
			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"))
				{
					empCode		= genericUtility.getColumnValueFromNode("emp_code",currDetail);
					adCode		= genericUtility.getColumnValueFromNode("ad_code",currDetail);
					monthCode	= genericUtility.getColumnValueFromNode("month_code",currDetail);
					effDate		= genericUtility.getColumnValueFromNode("eff_date",currDetail);
					expDate		= genericUtility.getColumnValueFromNode("exp_date",currDetail);

					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;
					pstmt.close();
					pstmt = null;
					keyString = empCode + "|" + monthCode+ "|" + adCode + "|" + effectiveDate ;
					System.out.println("keyString.....:: " + keyString);
					errorCode = admCommon.payarrToProcUpdation(periodFrom, periodTo, empCode, empCode, "AR", "W_EMP_MTHAD", keyString, null, 0, null, null, xtraParams, conn);
					if (errorCode.trim().length() > 0)
					{
						conn.rollback();
						retString = itmDBAccessEJB.getErrorString("",errorCode,userId);
						System.out.println("Ret String: " + retString);
					}
					else if (errorCode.trim().length() == 0)
					{
						conn.commit();
					}
				}
			}
		}
		catch (SQLException sqe)
		{
			System.out.println("The SQLException occurs in [EmpMthadPrsEJB] :: [executepreSaveRec] :"+sqe);
			sqe.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception sqe1){}
			throw new ITMException(sqe);
		}
		catch(Exception e)
		{
			System.out.println("The Exception occurs in [EmpMthadPrsEJB] :: [executepreSaveRec] :"+e);			
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1){}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing stmt and pstmt......");
				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 :[EmpMthadPrsEJB] :: [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;		
	}	
}