package ibase.webitm.ejb.adm;
//16032007

import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.TransIDGenerator;//TID
import ibase.utility.CommonConstants;//TID

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

@Stateless // added for ejb3
public class EmployeeOt extends ValidatorEJB implements EmployeeOtLocal,EmployeeOtRemote // SessionBean
{
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	GenericUtility genericUtility = GenericUtility.getInstance();
	
	Connection conn = null;
	
	String chgUser = null;  
	String chgTerm  = null;
	
	String loginSite = null;
	String userId = null;
	String empCodeAprv = null;
	
	/*public void ejbCreate() throws RemoteException, CreateException{System.out.println("PayRollVoucEJB  ...........................");}
	public void ejbRemove(){}
	public void ejbActivate(){}
	public void ejbPassivate(){}*/
	public String wfValData() throws RemoteException,ITMException{return "";}
	public String itemChanged() throws RemoteException,ITMException{return "";}
	//ItemChange 
	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		try
		{
		
			System.out.println("xmlString:::" + xmlString);
			System.out.println("xmlString1:::" + xmlString1);
			System.out.println("xmlString2:::" + xmlString2);
			dom1 = parseString(xmlString1); 
			dom = parseString(xmlString); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [EmployeeOtEJB][itemChanged(String,String)] :==>\n"+e.getMessage());
		}
        return valueXmlString; 
	}
	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		
		String prdCode = null;
		System.out.println("Item Changes Call..................");
		NodeList parentNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		NodeList childNodeList = null;
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		empCodeAprv= getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
		loginSite = getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
		prdCode = getValueFromXTRA_PARAMS(xtraParams,"prdCode");
		StringBuffer valueXmlString = new StringBuffer();
		ResultSet rs =null;
		PreparedStatement pstmt = null;
		String empCode = null;
		int n;
		int currentFormNo = 0;
		int ctr = 0;
		String errCode = "";
		String errString = "";
		String sql = "";
		String columnValue = "";
		String childNodeName = "";
		
		System.out.println("xtraParams::::::::::::::::"+xtraParams);
		try
		{
			if(conn == null)
			{ 
				conn = getConnection(); 
			}
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");
			System.out.println("Form No:::"+currentFormNo);							
			switch (currentFormNo)
			{
				case 2:
//	     			SEARCHING THE DOM FOR THE INCOMING COLUMN VALUE START
					parentNodeList = dom.getElementsByTagName("Detail2");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					int childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue().trim();
							}
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					System.out.println("current column="+currentColumn);
					valueXmlString.append("<Detail2>");	
					 if (currentColumn.trim().equalsIgnoreCase("ot_date"))
					{
						String shift =null;
						String dayNo =null;
						double fdHour =0;
						String otDateStr = getValidDateTimeString(columnValue, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
						Timestamp otDate = java.sql.Timestamp.valueOf(otDateStr + " 00:00:00");
						
					/*	Calendar cal = Calendar.getInstance();
						cal.setTime(otDate);
						System.out.println("Day no :["+cal.get(Calendar.DAY_OF_WEEK)+"]");*/
						
						sql = "SELECT SHIFT,DAY_NO   FROM ATTENDANCE_DAY WHERE ATTD_DATE = ? AND EMP_CODE =  '"+getColumnValue("emp_code",dom,"2")+"'";
						System.out.println("Sql:"+sql);
						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1,otDate);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							shift = (rs.getString(1)==null?"  ":rs.getString(1));
							dayNo =(rs.getString(2)==null?"  ":rs.getString(2));
						}
						rs.close();
						pstmt.close();
						sql = "SELECT FD_HRS  FROM WORKSHFT WHERE DAY_NO ='"+dayNo+"' AND SHIFT = '"+shift+"'";
						System.out.println("Sql:"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							fdHour = rs.getDouble(1);
						}
						valueXmlString.append("<shift>").append(shift).append("</shift>\r\n");
						valueXmlString.append("<day_no>").append(dayNo).append("</day_no>\r\n");
						valueXmlString.append("<shift_time>").append(new Double(fdHour)).append("</shift_time>\r\n");
						
						
						
					}
					else if (currentColumn.trim().equalsIgnoreCase("ot_time"))
					{
						valueXmlString.append("<cal_ot_time>").append(getColumnValue("ot_time",dom,"2")).append("</cal_ot_time>\r\n");
					}
					
					else if (currentColumn.trim().equalsIgnoreCase("itm_default"))
					{
						
						String FName=" ";
						String LName = "  ";
						String FullName =null;
						
						sql = "SELECT EMP_FNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+getColumnValue("emp_code",dom1)+"'";
						System.out.println("Emp Name Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							FName = (rs.getString(1)==null?"  ":rs.getString(1));
							LName =(rs.getString(2)==null?"  ":rs.getString(2));
						}
						FullName = FName+LName;
						rs.close();
						pstmt.close();
						valueXmlString.append("<emp_code>").append(getColumnValue("emp_code",dom1)).append("</emp_code>\r\n");
						valueXmlString.append("<emp_fname>").append(FName).append("</emp_fname>\r\n");
						valueXmlString.append("<emp_lname>").append(LName).append("</emp_lname>\r\n");
						valueXmlString.append("</Detail2>\r\n");
							
					}
					
					
					break;
					case 1:
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					int childListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue();
							} 
	 					}
						ctr++;
					}while(ctr < childListLength && !childNodeName.equals(currentColumn));
					System.out.println("current column="+currentColumn);
					valueXmlString.append("<Detail1>");	
					if (currentColumn.trim().equalsIgnoreCase("itm_default"))
					{
							String periodStr = getValidDateTimeString(getCurrdateAppFormat(), genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
							Timestamp periodTs = java.sql.Timestamp.valueOf(periodStr + " 00:00:00");
							sql = "SELECT CODE FROM PERIOD WHERE  ? BETWEEN  FR_DATE AND TO_DATE " ;
							System.out.println("Payroll_projdet:::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
				 			System.out.println("Laps Date:{"+periodTs+"]");
							pstmt.setTimestamp(1,periodTs);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								prdCode = rs.getString(1);
								System.out.println("Period is ["+prdCode+"]");
							}
							rs.close();
							pstmt.close();
							
							valueXmlString.append("<status_date>").append(getCurrdateAppFormat()).append("</status_date>\r\n");
							valueXmlString.append("<ot_hours>").append("0").append("</ot_hours>\r\n");
							valueXmlString.append("<cal_ot_hours>").append("0").append("</cal_ot_hours>\r\n");
							valueXmlString.append("<ot_date>").append(getCurrdateAppFormat()).append("</ot_date>\r\n");
							valueXmlString.append("<prd_code>").append(prdCode).append("</prd_code>\r\n");
							valueXmlString.append("<flag>").append("D").append("</flag>\r\n");
							
							valueXmlString.append("</Detail1>\r\n");
							
					}
					else if (currentColumn.trim().equalsIgnoreCase("emp_code"))
					{
						String FName=" ";
						String LName = "  ";
						String FullName =null;
						
						sql = "SELECT EMP_FNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+columnValue.trim()+"'";;
						System.out.println("Emp Name Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							FName = (rs.getString(1)==null?"  ":rs.getString(1));
							LName =(rs.getString(2)==null?"  ":rs.getString(2));
						}
						FullName = FName+LName;
						rs.close();
						pstmt.close();
						valueXmlString.append("<emp_fname>").append(FullName).append("</emp_fname>\r\n");
						valueXmlString.append("<employee_emp_lname>").append(FullName).append("</employee_emp_lname>\r\n");
						valueXmlString.append("</Detail1>\r\n");
					}
					else if (currentColumn.trim().equalsIgnoreCase("ot_date"))
					{
							String periodStr = getValidDateTimeString(getColumnValue("ot_date",dom,"1"), genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
							Timestamp periodTs = java.sql.Timestamp.valueOf(periodStr + " 00:00:00");
							sql = "SELECT CODE FROM PERIOD WHERE  ? BETWEEN  FR_DATE AND TO_DATE " ;
							System.out.println("Payroll_projdet:::["+sql+"]");
							pstmt = conn.prepareStatement(sql);
							System.out.println("Period Date:{"+periodTs+"]");
							pstmt.setTimestamp(1,periodTs);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								prdCode = rs.getString(1);
								System.out.println("Period is ["+prdCode+"]");
							}
							periodTs =null;
							periodStr =null;
							
							rs.close();
							pstmt.close();
							valueXmlString.append("<prd_code>").append(prdCode).append("</prd_code>\r\n");
					}
				
				
					//break;
				}//END OF SWITCH
				valueXmlString.append("</Root>");	
				System.out.println("valueXmlString:::"+valueXmlString);
			}//END OF TRY
		
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			e.printStackTrace();
		} 
		return valueXmlString.toString();
	}//END OF ITEMCHNGE
	public String getValidDateTimeString(String dateTimeStr, String sourceDateTimeFormat, String targetDateTimeFormat) throws ITMException
	{
		System.out.println("Getting the valid datetime string for dateTimeStr :"+dateTimeStr+": which is in format :"+sourceDateTimeFormat);
		Object date = null;
		String retDateStr = "";
		try
		{
			if (!(sourceDateTimeFormat.equalsIgnoreCase(targetDateTimeFormat)))
			{
				if (sourceDateTimeFormat.indexOf("/") != -1)
				{
					dateTimeStr.replace('/', '-');
				}
				else if (sourceDateTimeFormat.indexOf(".") != -1)
				{
					dateTimeStr.replace('.', '-');
				}
				date = new SimpleDateFormat(sourceDateTimeFormat).parse(dateTimeStr);
				SimpleDateFormat sdfOutput = new SimpleDateFormat(targetDateTimeFormat);
				retDateStr = sdfOutput.format(date);
			}
			else
			{
				retDateStr = dateTimeStr;
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception :GenericUtility :getValidDateString :==>"+e.getMessage());
			throw new ITMException(e);
		}
		System.out.println("retDateStr :"+retDateStr);
		return retDateStr;
	}
	private String getCurrdateAppFormat()
	{
		String currAppdate ="";
		java.sql.Timestamp currDate = null;
		try
		{
				Object date = null;
				currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
				System.out.println(genericUtility.getDBDateFormat());
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = sdf.parse(currDate.toString());
				currDate =	java.sql.Timestamp.valueOf(sdf.format(date).toString() + " 00:00:00.0");
				currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
		}
		catch(Exception e)
		{
			 
			System.out.println("Exception in :::calcFrsBal"+e.getMessage());
		}
		return (currAppdate);
	}
	
	private  String getCurrdateAppFormat(java.sql.Timestamp ts)
	{
		String dateAf ="";
		System.out.println("Comming Date[In DB Format] :::"+ts.toString());
		try
		{
				Object date = null;
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = sdf.parse(ts.toString());
				dateAf = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(date).toString();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("Retturning Date :::"+dateAf);
		return (dateAf);
	}
	
}//end of ejb