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.system.config.ConnDriver;
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 AttendanceWorkBal extends ValidatorEJB implements	AttendanceWorkBalLocal,AttendanceWorkBalRemote // SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	ConnDriver connDriver = new ConnDriver();
	/*
	public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Entering into AttendancesEJB.............");
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}
	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	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  ");
		StringBuffer valueXmlString = new StringBuffer();
		StringBuffer retString = new StringBuffer();
		String errCode = "";
		String sql = "";
		String sundrySql= "";
		String columnValue = "";
		String loginSite = "";
		String format = "";
		String accPrd = "";
		String childNodeName = "";
		String dateStr="";
		String endDateStr="";
		String endTime=null;
		String stsrtTime=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);
		System.out.println("currentColumn ::-"+currentColumn);
		try
		{
			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>");
			switch (currentFormNo)
			{
				case 1:
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					valueXmlString.append("<Detail1>");			
					if(currentColumn.trim().equals("itm_default"))
					{
						Calendar cal=Calendar.getInstance();
						Date date=cal.getTime();
						SimpleDateFormat dateFormat=new SimpleDateFormat(genericUtility.getApplDateFormat());
						dateStr=dateFormat.format(date); 
						System.out.println("Today's Date "+dateStr);
						valueXmlString.append("<start_date>").append(dateStr).append("</start_date>\r\n");
					}
					/*else
					if(currentColumn.trim().equals("end_date") || currentColumn.trim().equals("start_date"))
					{
						parentNodeList = dom.getElementsByTagName("Detail1");
						parentNode = parentNodeList.item(0);
						childNodeList = parentNode.getChildNodes();
						ctr = 0;
						childListLength = childNodeList.getLength();
						while(ctr<childListLength)
						{
							String  dateString=childNodeList.item(ctr).getNodeName();
							if("end_date".equals(dateString))
							endTime=childNodeList.item(ctr).getFirstChild().getNodeValue();
							else
							if("start_date".equals(dateString))
							stsrtTime=childNodeList.item(ctr).getFirstChild().getNodeValue();
							ctr++;
						}
						if(endTime.indexOf(' ')!=-1)
						{
							endTime=endTime.substring(0,endTime.indexOf(' '));
						}
						if(stsrtTime.indexOf(' ')!=-1)
						{
							stsrtTime=stsrtTime.substring(0,stsrtTime.indexOf(' '));
						}
						if(endTime.indexOf('-')!=-1)
						{
							endTime=endTime.replace('-','/');
						}
						if(stsrtTime.indexOf('-')!=-1)
						{
							stsrtTime=stsrtTime.replace('-','/');
						}
						System.out.println(">>>>>>.. endTime "+endTime); 
						System.out.println(">>>>>>.. stsrtTime "+stsrtTime); 
						if(stsrtTime !=null && endTime !=null)
						{
							SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat()); 
							Date stDate = simpleDateFormat.parse(stsrtTime);
							Date edDate = simpleDateFormat.parse(endTime);
						//	Date stDate = new Date(stsrtTime);
						//	Date edDate = new Date(endTime);
							long stTimeImMilsec=stDate.getTime();
							long edTimeImMilsec=edDate.getTime();
							long dayTminMilsec=24*60*60*1000;
							long noOfDays =(edTimeImMilsec - stTimeImMilsec)/dayTminMilsec;
							if(noOfDays !=0)
							{
								noOfDays=noOfDays + 1;
							}
							System.out.println(">>>>>>.. stTimeImMilsec "+stTimeImMilsec); 
							System.out.println(">>>>>>.. edTimeImMilsec "+edTimeImMilsec); 
							System.out.println(">>>>>>.. noOfDays "+noOfDays); 
							valueXmlString.append("<paid_prdcode>").append(noOfDays).append("</paid_prdcode>\r\n");
						}
					}*/
					valueXmlString.append("</Detail1>\r\n");
					break;
				} 
				valueXmlString.append("</Root>");	
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			e.printStackTrace();
		}	
		return valueXmlString.toString();
	}
	private long getTimeInMinit(String timeStr)
	{
		String hr=timeStr.substring(0,timeStr.indexOf(':'));
		String min=timeStr.substring(timeStr.indexOf(':')+1);
		long timinMin=Integer.parseInt(hr)*60+Integer.parseInt(min);
		return timinMin;
	}
	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 = null;
		System.out.println("Entering into  validations ...................");
		System.out.println("xmlString  : "+xmlString);
		System.out.println("xmlString1  : "+xmlString1);
		System.out.println("xmlString2  : "+xmlString2);
		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
	{
		System.out.println("  IN wfValData 2");
		Connection conn = null;
		Statement stmt = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String errString = "";
		String errCode = "";
		String sql = "";
		String userId = ""; 
		String loginSite = "";
		String startDateStr = "";
		String endDateStr = "";
		String shiftPattern = "";
		String periodCode = "";
		String itemSer = "";
		String currCode = "";
		String childNodeName = ""; 
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr,currentFormNo=0;
		int childNodeListLength;
		int cnt;
		Date startDate=null;
		Date endDate=null;
		String workTblNo = ""; 
		int lineNo = 0;
		String lineNoStr = "";
		SimpleDateFormat simpleDateFormat = null;
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		try
		{
			conn = getConnection(); 
			simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			parentNodeList = dom.getElementsByTagName("Detail" + currentFormNo);
			startDateStr = genericUtility.getColumnValue("start_date",dom);
			endDateStr = genericUtility.getColumnValue("end_date",dom);
			workTblNo = genericUtility.getColumnValue("work_tblno",dom);
			
			lineNoStr = genericUtility.getColumnValue("line_no",dom);
			System.out.println("Line No : "+lineNoStr);
			if(lineNoStr != null && lineNoStr.trim().length() > 0){
				lineNo = Integer.parseInt(lineNoStr);
			}			
			if(startDateStr !=null && endDateStr !=null)
			{
				if(startDateStr.indexOf(" ")!= -1)
				{
					startDateStr=startDateStr.substring(0,startDateStr.indexOf(" "));
				}
				if(endDateStr.indexOf(" ")!=-1)
				{
					endDateStr=endDateStr.substring(0,endDateStr.indexOf(" "));
				}
				if(startDateStr.indexOf('-')!=-1)
				{
					startDateStr=startDateStr.replace('-','/');
				}
				if(endDateStr.indexOf('-')!=-1)
				{
					endDateStr=endDateStr.replace('-','/');
				}
				startDate = simpleDateFormat.parse(startDateStr);
				endDate = simpleDateFormat.parse(endDateStr);
			}
			parentNode = parentNodeList.item(0);
			childNodeList = parentNode.getChildNodes();
			childNodeListLength = childNodeList.getLength();
			for (ctr = 0; ctr < childNodeListLength; ctr++)
			{
				childNode = childNodeList.item(ctr);
				childNodeName = childNode.getNodeName();
				switch (currentFormNo)
				{
					case 1:
					
						//if (childNodeName.equals("paid_prdcode"))
						if (childNodeName.equals("prd_code__pay"))		
						{
							if (childNode.getFirstChild() == null)
							{
								errCode = "VTCALPRD";
								errString = getErrorString("prd_code__pay",errCode,userId);
								break;
							}
							periodCode=childNode.getFirstChild().getNodeValue();
							sql = "SELECT COUNT(*) AS COUNT FROM PERIOD WHERE CODE = '"+periodCode+"'";
							stmt = conn.createStatement();
							rs = stmt.executeQuery(sql);
							if (rs.next())
							{
								cnt = rs.getInt("COUNT");
								if (cnt == 0)
								{
									errCode = "STARTPRD";
									errString = getErrorString("prd_code__pay",errCode,userId);
									break;
								}
							}
							stmt.close();
							rs.close();

						}
						else
						if((startDateStr ==null)) 
						{
							errCode = "VEDAT2";
							errString = getErrorString("start_date",errCode,userId);
							break;
						}
						else
						if((endDateStr ==null)) 
						{
							errCode = "VEDAT2";
							errString = getErrorString("end_date",errCode,userId);
							break;
						}
						else
						if((endDate.compareTo(startDate) <= 0)) 
						{
							errCode = "VTDATE1";
							errString = getErrorString("end_date",errCode,userId);
							break;
						}
						else
						if (childNodeName.equals("start_date") || childNodeName.equals("end_date")){
							if(editFlag.equalsIgnoreCase("E")){
								java.sql.Date  dbFrDate = new java.sql.Date(System.currentTimeMillis());
								java.sql.Date  dbToDate = new java.sql.Date(System.currentTimeMillis());
								sql = "SELECT START_DATE,END_DATE FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"' AND LINE_NO = "+lineNo+"";
								System.out.println("SQL :: "+sql);
								stmt = conn.createStatement();
								rs = stmt.executeQuery(sql);
								if(rs.next()){
									dbFrDate = rs.getDate("START_DATE");
									dbToDate = rs.getDate("END_DATE");
									
									System.out.println("DomFrDate : "+startDate+" DbFromDate :"+dbFrDate+" DomEndDate :"+endDate+" dbEndDate :"+dbToDate);
									if(startDate.compareTo(new java.util.Date(dbFrDate.getTime())) == 0 && endDate.compareTo(new java.util.Date(dbToDate.getTime())) == 0){
										break;
									}
								}
								stmt.close();
							}
							int count = 0;
								
							java.sql.Date startSqlDate = new java.sql.Date(startDate.getTime());	
							java.sql.Date endSqlDate = new java.sql.Date(endDate.getTime());
							
							System.out.println("Work Table No ::"+workTblNo);
							if(workTblNo != null && workTblNo.trim().length() > 0){
								sql = "SELECT COUNT(*) FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"'";
								System.out.println("SQL ::"+sql);
								stmt = conn.createStatement();
								rs = stmt.executeQuery(sql);
								if(rs.next()){
									count = rs.getInt(1);
									if(count > 0){
										sql = "SELECT COUNT(*) FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"' "+
											"AND ? BETWEEN START_DATE AND END_DATE AND LINE_NO != "+lineNo+"";
										System.out.println("SQL ::"+sql);
										pstmt = conn.prepareStatement(sql);
										pstmt.setTimestamp(1,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(startDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
										System.out.println("SET 1 "+Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(startDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
										rs = pstmt.executeQuery();
										if(rs.next()){
											count = rs.getInt(1);
										}
										System.out.println("Count ::"+count);
										if(count > 0){
											errCode = "VTINVOT";
											errString = getErrorString("start_date",errCode,userId);
											break;
										}																		
										else if(count == 0){
											sql = "SELECT COUNT(*) FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"' "+
											"AND ? BETWEEN START_DATE AND END_DATE AND LINE_NO != "+lineNo+"";
											pstmt = conn.prepareStatement(sql);
											pstmt.setTimestamp(1,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(endDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
											System.out.println("SET 1 "+Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(endDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
											rs = pstmt.executeQuery();
											if(rs.next()){
												count = rs.getInt(1);
											}
											System.out.println("Count ::"+count);
											if(count > 0){
												errCode = "VTINVOT";
												errString = getErrorString("end_date",errCode,userId);
													break;
											}
											else if(count == 0){
												sql = "SELECT COUNT(*) FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"' "+
												"AND START_DATE BETWEEN ? AND ? AND LINE_NO != "+lineNo+"";
												System.out.println("SQL ::"+sql);
												pstmt = conn.prepareStatement(sql);
												pstmt.setTimestamp(1,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(startDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
												pstmt.setTimestamp(2,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(endDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
												
												rs = pstmt.executeQuery();
												if(rs.next()){
													count = rs.getInt(1);
												}
												System.out.println("Count ::"+count);
												if(count > 0){
													errCode = "VTINVOT";
													errString = getErrorString("start_date",errCode,userId);
													break;
												}
												else if(count == 0){
													sql = "SELECT COUNT(*) FROM WORK_TABLE WHERE WORK_TBLNO = '"+workTblNo+"' "+
													"AND END_DATE BETWEEN ? AND ? AND LINE_NO != "+lineNo+"";
													System.out.println("SQL ::"+sql);
													pstmt = conn.prepareStatement(sql);
													pstmt.setTimestamp(1,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(startDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
													pstmt.setTimestamp(2,Timestamp.valueOf(genericUtility.getValidDateTimeString(simpleDateFormat.format(endDate),genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat())));
													
													rs = pstmt.executeQuery();
													if(rs.next()){
														count = rs.getInt(1);
													}
													System.out.println("Count ::"+count);
													if(count > 0){
														errCode = "VTINVOT";
														errString = getErrorString("start_date",errCode,userId);
														break;
													}
												}		
											}		
										}
										
									}
								}
							}														
						}					
				}				
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception ::"+e);
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(stmt != null){
					stmt.close();
					stmt = null;
				}
				if(pstmt != null){
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
				}
			}
			catch(Exception ex)
			{
				System.out.println("Exception ::"+ex.getMessage());
				ex.printStackTrace();
			}
		}
		return errString;
	}
}