package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;

import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.ejb.*;
import org.w3c.dom.*;

import ibase.system.config.ConnDriver;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import javax.ejb.Stateless; // added for ejb3

@Stateless 
public class PfNumberprs extends ValidatorEJB implements  PfNumberprsLocal,PfNumberprsRemote
{
	String retString = "";
	String objName = "";		
	Document domStr = null;
	ResultSet rs = null;		
	PreparedStatement pstmt = null;
	String sql = "";
	String bookType = "";

	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	public String itemChanged() throws RemoteException, ITMException
	{
		return "";
	}
	public String itemChanged(String currXmlDataStr, String hdrXmlDataStr, String allXmlDataStr, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		System.out.println ( "HELLO_");
		Document currDom = null;
		Document hdrDom = null;
		Document hdrDomNew = null;
		Document allDom = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if (currXmlDataStr != null && currXmlDataStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currXmlDataStr); 
			}
			if (hdrXmlDataStr != null && hdrXmlDataStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrXmlDataStr); 
			}
			if (allXmlDataStr != null && allXmlDataStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :DocMasMapEJB :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from DocMasMapEJB itemChanged" );
		return errString;
	}


	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String sql = "";
		String columnValue = "";
		String userId = "";
		String docDescr="";
		String docNameDescr="";
		String empCode = "";
		String empFname = "";
		String empMname = "";
		String empLname = "";
		String designation = "";
		String reportTo = "";
		String reportToAdmin = "";
		String departmentDescr = "";
		String reportToAdminFname = "";
		String outTime = "";
		long strIn_timeLong = 0;
		long strOut_timeLong = 0;
		StringBuffer valueXmlString = new StringBuffer();
		Connection connObject = null;
		PreparedStatement pstmt = null;
		ResultSet rSet = null;
		int currentFormNo = 0;
		int count=0;
		java.sql.Date currentDate = null;
		String retDateStr = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		String confirmed = "";
		String statusDate1 = "";
		String statusDate = "";
		
		String childNodeName = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;		
		Node parentNode = null;
		Node childNode = null;
		int childNodeListLength = 0;
		int ctr = 0;
		
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			DateFormat dateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			java.util.Date todayDt = new java.util.Date();
			String todayDateStr = dateFormat.format(todayDt);
			System.out.println("todayDateStr date testing"+todayDateStr);
			statusDate1 =  genericUtility.getValidDateString(todayDateStr,genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
			System.out.println("statusDate1 date testing"+statusDate1);
			statusDate = todayDateStr;
			System.out.println("status date testing"+statusDate + " 00:00:00");
			System.out.println("editFlag="+editFlag);
			userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			connObject = connDriver.getConnectDB("DriverValidator");
			parentNodeList = currDom.getElementsByTagName("Detail1");
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			valueXmlString.append("<Detail1>");
			childNodeListLength = childNodeList.getLength();
			do 
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				ctr++;
			}
			while (ctr < childNodeListLength && !childNodeName.equals(currentColumn));	
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
			valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n" );
			columnValue = genericUtility.getColumnValue(currentColumn, currDom);
			valueXmlString.append( "<Detail1>\r\n" );
			if(currentColumn.trim().equalsIgnoreCase("itm_default") || currentColumn.trim().equalsIgnoreCase("itm_defaultedit") )
			{
				System.out.println(" tran date value"+statusDate);
				valueXmlString.append( "<tran_date><![CDATA[" ).append( statusDate ).append( "]]></tran_date>\r\n" );
			}
			//Added by Hemlata[16/07/2014][For setting site code based on emp code].Start
			else if (currentColumn.trim().equals("emp_code"))
			{
				if(columnValue !=null && columnValue.trim().length() >0)
				{
					sql="SELECT PAY_SITE FROM EMPLOYEE WHERE EMP_CODE= ? ";
					System.out.println("*SQL:****************"+sql);
					pstmt = connObject.prepareStatement( sql );	
					pstmt.setString(1,columnValue);
					rs = pstmt.executeQuery();	
					String paySite ="";
					if( rs.next())
					{
						 paySite =checkNull(rs.getString("PAY_SITE"));				
					}	
					valueXmlString.append( "<emp_code><![CDATA[" ).append( columnValue ).append( "]]></emp_code>\r\n" );
					valueXmlString.append( "<site_code><![CDATA[" ).append( paySite ).append( "]]></site_code>\r\n" );
				}
				else
				{
					valueXmlString.append("<site_code><![CDATA[]]></site_code>\r\n");
				}
					
			}
//			Added by Hemlata[16/07/2014][For setting site code based on emp code].End
			valueXmlString.append( "</Detail1>\r\n" );
		}//End of TRY itemChanged doc
		catch(Exception e)
		{
			System.out.println( "Exception :DocMasMapEJB :itemChanged:" + e.getMessage() + ":" );
			throw new ITMException(e);
		}//End of Catch
		finally
		{
			try
			{
				if( rSet != null )
				{
					rSet.close();
					rSet = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( connObject != null && ! connObject.isClosed() )
				{
					connObject.close();
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :DocMasMapEJB:itemChanged :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}//End of Finally
		valueXmlString.append( "</Root>\r\n" );	
		return valueXmlString.toString();
	}//End of Item changed

  // To check Columnvalue is null or not
	private String checkNull( String input )
	{
		if (input == null)
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}	
	
	public String preSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String preSave(String domString, String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;		
		NodeList childNodeList = null;
		Node childNode = null;		
		Node parentNode = null;

		int parentNodeListLength = 0;		
		int childNodeListLen = 0;
		int childNodeListLength = 0;

		String childNodeName = "";

		String refLineNum = null;
		String bkRefLineNum = null;
		String lineNum = null;
		String lineNum3 = null;
		String lineNum4 = null;
		String errString = null;
		String updateFlag="";
		int roomCnt = 0;
		int banqCnt = 0;
		double payContr = 0.0;
		Document domStr = null;
		String updtFlag="";
		String status = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null ;
		String sqlQuery="";
		String key="REQ";
		String val="";
		int count=0;
		double countBudget = 0.0;
		String budgetShare = "";
		ArrayList sumArrList =new ArrayList();

		String acctCode = null;
		String deptCode = null;
		String cctrCode = null;
		String analCode = null;
		String checkStr = null;
		String confHall = "";
		String eventName = "";
		String prefHtlBudg = "";
		String keyStr = "";
		ArrayList checkArrayList = new ArrayList();
		String sqlStr = null;
		String empCode = "";
		String pfNum = "";
		Statement stmt = null;
		String errorCode = null;
		String userId = null;
		String tranDate = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("Pre_Save start");
			if (domString != null && domString.trim().length() != 0 )
			{
				domStr = parseString(domString);
			}
			parentNodeList = domStr.getElementsByTagName("Detail1");
			parentNodeListLength = parentNodeList.getLength();
			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);

				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();

				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					//	updtFlag = getAttribValue(parentNode,"attribute", "updateFlag");
					if(!updtFlag.equalsIgnoreCase("D"))
					{	
						if(childNode.getFirstChild()!=null)
						{
							if (childNodeName.equals("emp_code")) 
							{
								empCode = (childNode.getFirstChild().getNodeValue().trim());
								System.out.println("Inside presave empCode"+empCode);
							}
							else if (childNodeName.equals("tran_date")) 
							{
								tranDate = (childNode.getFirstChild().getNodeValue().trim());
								System.out.println("Inside presave tranDate"+tranDate);
							}
							else if (childNodeName.equals("pf_no")) 
							{
								pfNum = (childNode.getFirstChild().getNodeValue().trim());
								System.out.println("Inside presave pfNum"+pfNum);
							}
						}
					}
				}
			}
			if(tranDate == null || tranDate.trim().length() <= 0 )
			{
				String errCode = "VTBLKCHDTE";
				errString=getError("Tran date should not be left blank",errCode,conn);
				return errString;
			}
			if(empCode == null || empCode.trim().length() <= 0 )
			{
				String errCode = "VTBLKCHODN";
				errString=getError("Employee code should not be left blank",errCode,conn);
				return errString;
			}
			else if(empCode != null && empCode.trim().length() > 0)
			{
				sql = "SELECT COUNT(*) AS COUNT FROM EMPLOYEE WHERE EMP_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, empCode);
				rs = pstmt.executeQuery();
				if (rs.next()) 
				{
					count = rs.getInt("COUNT");
				}
				if (count == 0)
				{
					String errCode = "VTINVCHODN";
					errString=getError("Invalid employee code, please enter valid employee code",errCode,conn);
					return errString;
				}
			}
			if(pfNum == null || pfNum.trim().length() <= 0 )
			{
				String errCode = "VTBLKPFODN";
				errString=getError("Pf number should not be left blank",errCode,conn);
				return errString;

			}
			if(empCode != null && empCode.trim().length() > 0 && pfNum != null && pfNum.trim().length() > 0)
			{
				sqlStr = "UPDATE EMPLOYEE SET  PF_NO = '"+pfNum+"'  WHERE EMP_CODE = '"+empCode+"' ";
				System.out.println("sqlStr.........:: " + sqlStr);
				stmt = conn.createStatement();
				count = stmt.executeUpdate(sqlStr);

				conn.commit();
			}//End Of if(empStatus)
		}//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 getError(String descr,String Code,Connection conn) 
			throws ITMException, Exception
			{
		String mainStr ="";

		try
		{
			String errString = "";
			errString =  new ITMDBAccessEJB().getErrorString("",Code,"","",conn);
			String begPart = errString.substring(0,errString.indexOf("<message>")+9);
			String endDesc = errString.substring(errString.indexOf("</description>"));
			mainStr= begPart+"Invalid Data"+"</message><description>";
			mainStr= mainStr+" "+descr+" "+endDesc;
			System.out.println("mainStr:::::::::::::::::: "+mainStr);
			begPart = null;


		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return mainStr;
			}
	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;		
	}	
}
