package ibase.webitm.ejb.adm;
 
import java.rmi.RemoteException; 
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;
import org.w3c.dom.*;

import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.webitm.ejb.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class AttendanceAttdDedn extends ValidatorEJB implements  AttendanceAttdDednLocal,AttendanceAttdDednRemote // SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Entering into AttendancesEJB.............");
	} 
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	
	public String wfValData() throws RemoteException,ITMException
	{
		System.out.println(">>>>>>>>>  IN wfValData 1");
		return "";
	}

	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("  IN wfValData 2");
		Document dom = null;   
		Document dom1 = null;
		Document dom2 = null;
		String  errString = null;
		System.out.println(" xmlString  "+xmlString);
		System.out.println(" xmlString1  "+xmlString1);
		System.out.println(" xmlString2  "+xmlString2);
		System.out.println("Entering into  validations ...................");
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : PayableOpeningsEJB : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}

	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errCode = "";
		Connection conn = null;
		Statement stmt = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = ""; 
		String childNodeValue; 
		String  errString = null;
		String  startTimStr = null;
		String  endTimStr = null;
		int currentFormNo = 0;
		long startTime = 0;
		long endTime = 0;
		int childNodeListLength;
		ResultSet rs = null;
		String sql = "";
		String userId = ""; 
		int cnt;
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		try
		{
			conn = getConnection();
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("  currentFormNo "+currentFormNo);
			switch(currentFormNo)
			{
				case 1:
				{
					parentNodeList = dom1.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					childNodeListLength = childNodeList.getLength();
					System.out.println("childNodeListLength "+childNodeListLength);
					for(int ctr = 0; ctr < childNodeListLength; ctr++)
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						childNodeValue=null;
						if(childNode.getFirstChild()!=null)
						{
							childNodeValue = childNode.getFirstChild().getNodeValue();
						}
						if ("reason_code".equals(childNodeName))
						{
							int value = 0;
							if(childNodeValue==null)
							{
								errCode = "VRCDNULL";
								errString = getErrorString("reason_code",errCode,userId);
								break;
							}
							sql = "SELECT COUNT(*) FROM GENCODES WHERE MOD_NAME='W_ATTD_DEDN' AND FLD_NAME='REASON_CODE' AND FLD_VALUE = '"+childNodeValue.trim()+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							System.out.println("SQL : "+sql);
							if(rs.next())
							{
								value = rs.getInt(1);
							} 
							System.out.println("Reason Code Entered :"+childNodeValue+":"+" Count :"+value+":");
							if(value == 0)
							{
								errCode = "VRNEXIST";
								errString = getErrorString("reason_code",errCode,userId);
								break;
							}
							rs.close();
							stmt.close();							
						}
						else 
						if ("emp_code".equals(childNodeName))
						{
							if(childNodeValue == null)
							{
								errCode = "VEEMP2";
								errString = getErrorString("emp_code",errCode,userId);
								break;

							}
							sql = "SELECT COUNT(*) AS COUNT FROM Employee WHERE emp_code = '"+childNodeValue+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							if (rs.next())
							{
								cnt = rs.getInt("COUNT");
								System.out.println(">>>>>>>>>  cnt  "+cnt);
								if (cnt == 0)
								{
									errCode = "VEMPCD";
									errString = getErrorString("emp_code",errCode,userId);
									break;
								}
							}
							stmt.close();
							rs.close();
						}
						else 
						if ("start_time".equals(childNodeName))
						{
							startTimStr=childNodeValue;
							System.out.println(" startTimStr "+startTimStr);

						}
						else 
						if ("end_time".equals(childNodeName))
						{
							endTimStr=childNodeValue;
							System.out.println(" endTimStr "+endTimStr);

						}
					}
					if(startTimStr==null && errString == null)
					{
						errCode = "VSTTMN";
						errString = getErrorString("start_time",errCode,userId);
					}
					else
					if(endTimStr==null && errString == null)
					{
						errCode = "VEDTMN";
						errString = getErrorString("emp_code",errCode,userId);
					}
					else
					if(errString == null)
					{
						startTime=getTimeInMinit(startTimStr);
						endTime=getTimeInMinit(endTimStr);
						System.out.println(">>> startTime "+startTime);
						System.out.println(">>> endTime "+endTime);
						if(startTime > 24*60)
						{
							errCode = "VSTG";
							errString = getErrorString("start_time",errCode,userId);

						}
						else
						if(endTime > 24*60)
						{
							errCode = "VSEDG";
							errString = getErrorString("end_time",errCode,userId);

						}
						else
						if(startTime > endTime)
						{
							errCode = "VSTGED";
							errString = getErrorString("startTime",errCode,userId);
						}

					}
					System.out.println("errString "+errString);
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}	
		finally
		{
			try
			{
				if(conn != null)
				{
					conn.close();
				}
			}
			catch(Exception ex)
			{
				System.out.println("Exception ::"+ex.getMessage());
				ex.printStackTrace();
			}
		}
		return errString;		
	}

	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
		{
			dom = parseString(xmlString); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString :" + xmlString);
			dom1 = parseString(xmlString1); //returns the DOM Object for the passed XML Stirng
			System.out.println("xmlString1 :" + xmlString1);
			System.out.println("xmlString2 :" + xmlString2);
			
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [AttendancesEJB][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
	{
		System.out.println("  in itemChanged in addn ");
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSet rs1 = null;
		StringBuffer valueXmlString = null;  //new StringBuffer();
		StringBuffer retString = new StringBuffer();
		String errCode = "";
		String sql = "";
		String sundrySql= "";
		String columnValue = "";
		String loginSite = "";
		String format = "";
		String accPrd = "";
		String childNodeName = "";
		String  empcode="";
		String  empfname="";
		String  empmname="";
		String  emplname="";
		String  empcodeValue="";
		Connection conn = null;
		int childListLength=0;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		int n = 0;
		int currentFormNo = 0;

		String userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		System.out.println("userId ::-"+userId);
		loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
		System.out.println("loginSiteCode ::-"+loginSite);
		try
		{
			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>");
			valueXmlString.append("<Detail1>");	
			System.out.println("  currentFormNo "+currentFormNo);
			System.out.println("  currentColumn "+currentColumn);
			switch (currentFormNo)
			{
					case 1:
						parentNodeList = dom.getElementsByTagName("Detail1");
						parentNode = parentNodeList.item(0);
						childNodeList = parentNode.getChildNodes();
					if(currentColumn.trim().equals("itm_default"))
					{
						Calendar cal=Calendar.getInstance();
						Date date=cal.getTime();
						SimpleDateFormat dateFormat=new SimpleDateFormat(genericUtility.getApplDateFormat());
						String dateStr=dateFormat.format(date);
						System.out.println("Today's Date "+dateStr);
						valueXmlString.append("<dedn_date>").append(dateStr).append("</dedn_date>\r\n");
						valueXmlString.append("<start_time>").append("0.00").append("</start_time>\r\n");
						valueXmlString.append("<end_time>").append("0.00").append("</end_time>\r\n");
					}
					else 
					if(currentColumn.trim().equals("end_time") || currentColumn.trim().equals("start_time"))
					{
						ctr = 0;
						childListLength = childNodeList.getLength();
						String startTime = "";
						String endTime = "";
						
						startTime = GenericUtility.getInstance().getColumnValue("start_time",dom);
						endTime = GenericUtility.getInstance().getColumnValue("end_time",dom);
						
						System.out.println("StartTime :"+startTime );
						System.out.println("EndTime :"+endTime );
						if(startTime != null && startTime.trim().length() > 0 && endTime != null && endTime.trim().length() > 0)
						{
							long stTimeInMin=getTimeInMinit(startTime);
							long endTimeInMin=getTimeInMinit(endTime);
							System.out.println("stTimeInMin :"+stTimeInMin );
							System.out.println("endTimeInMin :"+endTimeInMin );
							if(stTimeInMin > 0 && endTimeInMin > 0)
							{
								if(stTimeInMin > endTimeInMin)
								{
									endTimeInMin = endTimeInMin + 1440;
								}
								long dednTime=endTimeInMin-stTimeInMin;
								valueXmlString.append("<dedn_time>").append(dednTime).append("</dedn_time>\r\n");
							}
						}						
					}
					else 
					if(currentColumn.trim().equals("emp_code"))
					{
						ctr = 0;
						 childListLength = childNodeList.getLength();
						while(ctr<childListLength)
						{
							  empcode=childNodeList.item(ctr).getNodeName();
							if("emp_code".equals(empcode))
							{
								if(childNodeList.item(ctr).getFirstChild() != null)
								{
									empcodeValue=childNodeList.item(ctr).getFirstChild().getNodeValue();
									sql="Select emp_fname,emp_mname,emp_lname from employee where emp_code='"+empcodeValue+"'";
									stmt = conn.createStatement();
									rs = stmt.executeQuery(sql);
									while(rs.next())
									{
										empfname=rs.getString("emp_fname");
										empmname=rs.getString("emp_mname");
										emplname=rs.getString("emp_lname");
									}
									stmt.close();
									rs.close();
								}

							}
							ctr++;
						}
						valueXmlString.append("<emp_fname>").append(empfname).append("</emp_fname>\r\n");
						valueXmlString.append("<emp_lname>").append(emplname).append("</emp_lname>\r\n");				
					}
					valueXmlString.append("</Detail1>\r\n");
					break;
			} 
			valueXmlString.append("</Root>");	
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			e.printStackTrace();
		}	
		finally
		{
			try
			{
				if(conn != null)
				{
					conn.close();
				}
			}
			catch(Exception ex)
			{
				System.out.println("Exception ::"+ex.getMessage());
				ex.printStackTrace();
			}


		}
		System.out.println("  Attd_dedn xml "+valueXmlString.toString());
		return valueXmlString.toString();
	}
	private long getTimeInMinit(String timeStr)
	{
		String tempTimeStr = timeStr;
		if(timeStr.indexOf('.') != -1){
			tempTimeStr =timeStr.substring(0,timeStr.indexOf('.'));
		}		 
		//String hr=timeStr.substring(0,timeStr.indexOf(':'));
		//String min=timeStr.substring(timeStr.indexOf(':')+1);
		String hr = tempTimeStr.substring(0,tempTimeStr.length()-2);
		String min = tempTimeStr.substring(tempTimeStr.length()-2,tempTimeStr.length());
		long timinMin=Integer.parseInt(hr)*60+Integer.parseInt(min);
		return timinMin;
	}

}
