package ibase.webitm.ejb.adm;

import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import java.rmi.RemoteException;
import java.util.*;
import java.text.*;
import java.sql.*;
import javax.ejb.*;
import org.w3c.dom.*;
import java.util.Calendar;
import java.util.Date;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class AttendanceTrace extends ValidatorEJB implements AttendanceTraceLocal,AttendanceTraceRemote	//SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called...");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String itemChanged() throws RemoteException,ITMException
	{
		System.out.println("itemChanged Called................");
		return "";
	}
	public String wfValData() throws RemoteException,ITMException
	{
		System.out.println("valdata Called....................");
		return "";
	}
	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{

		Document currentDom = null;
		Document headerDom = null;
		Document detailDom = null;
		String valueXmlString = "";
		try
		{
			currentDom	= parseString(xmlString);
			headerDom	= parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				detailDom = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(currentDom,headerDom,detailDom,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [AttendanceTraceEJB][itemChanged] :==>\n"+e.getMessage());
			e.printStackTrace();
		}
        return valueXmlString; 
	}
	public String itemChanged(Document currentDom, Document headerDom,Document detailDom, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet rsTemp = null;
		Statement stmtTemp = null;
		String sqlTemp = "";
		String errString = "";
		String userId = "";
		String empCode = "";
		String attdDate = "";
		String sql = "";
		String punchTime = "";
		String custCode = "";
		String custName = "";
		String inOutStatus = ""; //Gulzar 21/04/08
		String attDate = ""; //Gulzar 21/04/08

		int currentFormNo = 0;

		GenericUtility genericUtility = GenericUtility.getInstance();
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>");
		System.out.println("=================== Itemchange Starts =====================");
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getApplDateFormat());
			conn = getConnection();//Gets a Connection
			System.out.println("[AttendanceTraceEJB] [itemChanged] :currentFormNo ....." +currentFormNo);
			valueXmlString.append("<Root>");
			valueXmlString.append("<header>");
			valueXmlString.append("<editFlag>").append(editFlag).append("</editFlag>");
			valueXmlString.append("</header>");
			valueXmlString.append("<Detail>");		
			if (currentColumn.trim().equals("itm_default"))
			{
				java.util.Date currDate= new java.util.Date();
				attdDate = sdf.format(currDate);
				valueXmlString.append("<attd_date>").append(attdDate).append("</attd_date>");
				valueXmlString.append("<in_out>").append("I").append("</in_out>");
			}
			if (currentColumn.trim().equals("itm_defaultedit"))
			{
				custCode = genericUtility.getColumnValue("cust_code__visit",currentDom);
				custName = genericUtility.getColumnValue("cust_name__visit",currentDom);
				if ( custCode != null && custCode.trim().length() > 0 )
				{
					valueXmlString.append("<cust_name__visit protect = '1'>").append("<![CDATA["+custName+"]]>").append("</cust_name__visit>");
				}
			}
			if (currentColumn.trim().equals("emp_code"))
			{
				empCode = genericUtility.getColumnValue("emp_code",currentDom);
				attDate = genericUtility.getColumnValue("attd_date",currentDom); //Gulzar 21/04/08
				System.out.println("empCode................ :: " + empCode);
				sql = "SELECT EMP_FNAME, EMP_MNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+empCode+"'";
				System.out.println("sql :: " + sql);
				stmt = conn.createStatement();
				rs = stmt.executeQuery(sql);	
				if (rs.next())
				{
					valueXmlString.append("<emp_fname>").append(rs.getString("EMP_FNAME") == null ?"":rs.getString("EMP_FNAME")).append("</emp_fname>");
					valueXmlString.append("<emp_mname>").append(rs.getString("EMP_MNAME") == null ?"":rs.getString("EMP_MNAME")).append("</emp_mname>");
					valueXmlString.append("<emp_lname>").append(rs.getString("EMP_LNAME") == null ?"":rs.getString("EMP_LNAME")).append("</emp_lname>");
				}
				else
				{
					valueXmlString.append("<emp_fname>").append("").append("</emp_fname>");
					valueXmlString.append("<emp_mname>").append("").append("</emp_mname>");
					valueXmlString.append("<emp_lname>").append("").append("</emp_lname>");
				}
				rs.close();
				//Added by Gulzar - 21/04/08
				sql = "SELECT IN_OUT FROM ATTD_TRACE WHERE TRAN_ID = (SELECT MAX(TRAN_ID) FROM ATTD_TRACE WHERE EMP_CODE ='"+empCode+"' AND ATTD_DATE = ? )";
				System.out.println("sql :: " + sql);
				pstmt = conn.prepareStatement(sql);
				pstmt.setTimestamp(1,java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(attDate,genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
				rs = pstmt.executeQuery();
				if ( rs.next() )
				{
					inOutStatus = rs.getString("IN_OUT");
					if ( inOutStatus.equals("O") )
					{
						valueXmlString.append("<in_out>").append("I").append("</in_out>");
					}
					else
					{
						valueXmlString.append("<in_out>").append("O").append("</in_out>");
					}
				}
				else
				{
					valueXmlString.append("<in_out>").append("I").append("</in_out>");
				}
				rs.close();
				//End Add - Gulzar - 21/04/08

			}
			if (currentColumn.trim().equals("cust_code__visit"))
			{
				custCode = genericUtility.getColumnValue("cust_code__visit",currentDom);
				System.out.println("custCode................ :: " + custCode);
				if ( custCode != null && custCode.trim().length() > 0 )
				{
					if ( custCode.trim().equalsIgnoreCase("PRESALE") )//"PRESALE" Condition Added by Gulzar - 21/04/08
					{
						valueXmlString.append("<cust_name__visit>").append("Pre Sale Activities").append("</cust_name__visit>");
					}
					else
					{
						sql = "SELECT CUST_NAME FROM CUSTOMER WHERE CUST_CODE = '"+custCode+"'";
						System.out.println("sql :: " + sql);
						stmt = conn.createStatement();
						rs = stmt.executeQuery(sql);	
						if (rs.next())
						{
							valueXmlString.append("<cust_name__visit>").append("<![CDATA["+((rs.getString("CUST_NAME") == null) ?"":rs.getString("CUST_NAME"))+"]]>").append("</cust_name__visit>");
						}
						else
						{
							valueXmlString.append("<cust_name__visit>").append("").append("</cust_name__visit>");
						}
						rs.close();
					}
				}
				else
				{
					valueXmlString.append("<cust_name__visit>").append("").append("</cust_name__visit>");
				}
			}
			if (currentColumn.trim().equals("punch_time"))
			{
				try
				{
					String hourStr = "";
					String minuteStr = "";
					punchTime = genericUtility.getColumnValue("punch_time",currentDom);
					if ( punchTime != null && punchTime.trim().length() > 0 )
					{
						int index = punchTime.indexOf(":");
						int hour = 0;
						int minute = 0;
						if ( index != -1 )
						{
							hour = Integer.parseInt( punchTime.substring( 0, index ) );
							minute = Integer.parseInt( punchTime.substring( index+1 ) );
							/*
							if ( minute >= 60 )
							{
								int tempMin = minute;
								minute = minute-60;
								int tempHour = tempMin/60;
								if ( tempHour > 0)
								{
									hour += tempHour;
								}
							}
							if ( hour >= 24 )
							{
								hour = hour-24;
							}*/
							if ( hour < 10 )
							{
								hourStr = "0" + hour;
							}
							else
							{
								hourStr = "" + hour;
							}
							if ( minute < 10 )
							{
								minuteStr = "0" + minute;
							}
							else
							{
								minuteStr = "" + minute;
							}
						}
						else
						{
							if ( punchTime.trim().length() <= 2)
							{
								hour = Integer.parseInt( punchTime );
								if ( hour < 10 )
								{
									hourStr = "0" + hour;
									minuteStr = "00";
								}
								else
								{
									hourStr = "" + hour;
									minuteStr = "00";
								}
							}
							else
							{
								hourStr = "00";
								minuteStr = "00";
							}
						}
						punchTime = hourStr + ":" + minuteStr;
						valueXmlString.append("<punch_time>").append(punchTime).append("</punch_time>");
					}
					else
					{
						valueXmlString.append("<punch_time>").append("00:00").append("</punch_time>");
					}
				}
				catch(NumberFormatException nfe)
				{
					System.out.println("NumberFormatException Occurs...............");
				}
			}
			valueXmlString.append("</Detail></Root>");
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection...........");
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println("Exception in Closing Connection :: " + e);
			}
		}
		return valueXmlString.toString();
	}
    public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = " ";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{ 			
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString); 
			}
			if(xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = genericUtility.parseString(xmlString1); 
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = genericUtility.parseString(xmlString2); 
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
			System.out.println("ErrString :" + errString);		
		}
		catch(Exception e)
		{
			System.out.println("Exception :AttendanceTraceEJB :wfValData(String xmlString):" + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println("returning from AttendanceTraceEJB wfValData");
		return (errString);
	}

	public String wfValData(Document dom, Document dom1, Document dom2,String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String columnValue = null;
		String userId = null;
		String sql= null;
		String sql1 = null;
		String errString = " ";
		String empCode = "";
		String attdDate = "";
		String custCode = "";
		String custName = "";
		String inOut = "";
		String punchTime = "";
		String status = "";

		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;		
		int counterChild = 0;
		int noOfChilds = 0;
		int currentFormNo = 0;
		int count = 0;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");

			conn = getConnection(); //Gets a Connection
			
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			parentList = dom.getElementsByTagName("Detail" + currentFormNo);
			parentNode = parentList.item(0);
			childList = parentNode.getChildNodes();
			noOfChilds = childList.getLength();
			for(counterChild = 0; counterChild < noOfChilds; counterChild++)
			{
				childNode = childList.item(counterChild);
				childNodeName = childNode.getNodeName();
				if (childNodeName.equals("attd_date"))
				{
					attdDate = genericUtility.getColumnValue("attd_date",dom);
					System.out.println("attdDate :: " + attdDate);
					if ( attdDate == null || attdDate.trim().length() == 0 )
					{
						errString = getErrorString("attd_date","VEDAT2",userId);
						break;
					}
				}
				if (childNodeName.equals("emp_code"))
				{
					empCode = genericUtility.getColumnValue("emp_code",dom);
					sql = "SELECT STATUS FROM EMPLOYEE WHERE EMP_CODE = '"+empCode+"'";
					System.out.println("sql :: " + sql);
					stmt = conn.createStatement();
					rs = stmt.executeQuery(sql);	
					if (rs.next())
					{
						status = rs.getString("STATUS");
						if ( status != null && status.trim().length() > 0 )
						{
							errString = getErrorString("emp_code","VTRESIDT",userId);
							break;
						}
					}
					else
					{
						errString = getErrorString("emp_code","VMEMP1",userId);
						break;
					}
					rs.close();
				}
				if (childNodeName.equals("cust_code__visit"))
				{
					custCode = genericUtility.getColumnValue("cust_code__visit",dom);
					if ( custCode != null && custCode.trim().length() > 0 && (!custCode.trim().equalsIgnoreCase("PRESALE")) ) // "PRESALE" Condition Added - Gulzar - 21/04/08
					{
						sql = "SELECT COUNT(*) AS COUNT FROM CUSTOMER WHERE CUST_CODE = '"+custCode+"'";
						System.out.println("sql :: " + sql);
						stmt = conn.createStatement();
						rs = stmt.executeQuery(sql);	
						if (rs.next())
						{
							count = rs.getInt("COUNT");
						}
						rs.close();
						if ( count == 0 )
						{
							errString = getErrorString("cust_code__visit","VTCUSTCD1",userId);
							break;
						}
					}
				}
				if (childNodeName.equals("cust_name__visit"))
				{
					custName = genericUtility.getColumnValue("cust_name__visit",dom);
					if ( custName == null || custName.trim().length() == 0 )
					{
						errString = getErrorString("cust_name__visit","VTCUSTNAME",userId);
						break;
					}
				}
				if (childNodeName.equals("in_out"))
				{
					inOut = genericUtility.getColumnValue("in_out",dom);
					if ( inOut == null || inOut.trim().length() == 0 )
					{
						errString = getErrorString("in_out","VTINOUT",userId);
						break;
					}
				}
				if (childNodeName.equals("punch_time"))
				{
					try
					{
						punchTime = genericUtility.getColumnValue("punch_time",dom);
						if ( punchTime != null && punchTime.trim().length() > 0 )
						{
							int hour = 0;
							int minute = 0;
							int index = punchTime.indexOf(":");
							if ( index != -1 )
							{
								hour = Integer.parseInt( punchTime.substring( 0, index ) );
								minute = Integer.parseInt( punchTime.substring( index+1 ) );
								if ( ( hour == 0 || hour >= 24 ) || ( minute == 0 || minute >= 60 ) )
								{
									errString = getErrorString("punch_time","VTPNCHTIME",userId);
									break;
								}
							}
							else
							{
								errString = getErrorString("punch_time","VTPNCHTIME",userId);
								break;
							}
						}
						else
						{
							errString = getErrorString("punch_time","VTPNCHTIME",userId);
							break;
						}
					}
					catch(NumberFormatException nfe)
					{
						System.out.println("NumberFormatException Occurs.............");
						errString = getErrorString("punch_time","VTPNCHTIME",userId);
						break;
					}
				}
			}
		}//try ends here
		catch(Exception e)
		{
			System.out.println("Exception :AttendanceTraceEJB.java :wfValData(Document dom):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection...........");
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(stmt != null)
				{
					stmt.close();
					stmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e){}
		}
		return errString;
	}//wfValData(Document dom) method ends here
}
