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 ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import javax.naming.InitialContext;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
/*Created by Chetna on [04/09/2014] For Shift Rotate Change [Start]
 * */

@javax.ejb.Stateless


public class ShiftChangeIc  extends ValidatorEJB implements ShiftChangeIcLocal ,ShiftChangeIcRemote {
	
	GenericUtility genericUtility = GenericUtility.getInstance();

	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		try
		{
		
			
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("In wfValData Current xmlString="+xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("In wfValData Header xmlString1="+xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
				System.out.println("In wfValData All xmlString2="+xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document curDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("[ShiftChangeIc][wfValData(Document,Document,String,string,editflag)] :==>\n");
	 	String userId = "";
		String errorType = "";
		String childNodeName = null;
		String errCode = "";
		String shift ="";
		String empCode = "";
		String toDate = "";
		String fromDate = "";
		String errString = "";
		String msgType="";
		Date todt =null;
		Date frdt =null;
		
		int currentFormNo = 0;
		int childNodeListLength;
		int ctr=0;
		int count = 0;
		
		boolean flag = false;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;	
		Node parentNode = null;
		Node childNode = null;
	
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
	
		//StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>"); 
		StringBuffer errStringXml =  new StringBuffer("<?xml version=\"1.0\"?>\r\n<DocumentRoot>\r\n<description>Datawindow Root</description>\r\n<group0>\r\n<description>Group0 description</description>\r\n<Header0>\r\n<description>Header0 members</description>\r\n");
		
		try
		{
			
			SimpleDateFormat sdf =  new SimpleDateFormat(genericUtility.getApplDateFormat());
			
			
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			System.out.println("Current Form No. :- "+currentFormNo);
				
			switch(currentFormNo)
			{
			case 1 :
				parentNodeList = curDom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
			
				for(ctr = 0; ctr < childNodeListLength; ctr ++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase("emp_code"))     // Validation for emp code 
					{
						empCode = checkNull(genericUtility.getColumnValue("emp_code", curDom));
						if(empCode == null || empCode.trim().length() == 0)
						{
							errCode = "VPSHFTCH01";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
							msgType =  errorType(conn , "VPSHFTCH01" );
							if ( msgType.equalsIgnoreCase("E"))
							{
								break;
							}
						}
						else
						{
							flag = isRecordExist(conn," EMPLOYEE "," WHERE EMP_CODE ='"+empCode+"' AND  STATUS = 'S' ");
							
							if(flag == true)
							{
								errCode = "VPSHFTCH02";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							
								msgType =  errorType(conn , "VPSHFTCH02" );
								if ( msgType.equalsIgnoreCase("E"))
								{
									break;
								}
							}
						}
						
					}   //emp_code end
						
					else if(childNodeName.equalsIgnoreCase("from_dt")) // From Date 
					{
						fromDate = checkNull(genericUtility.getColumnValue("from_dt", curDom));
						
						if(fromDate == null || fromDate.trim().length() == 0)
						{
							errCode = "VPSHFTCH03";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
							msgType =  errorType(conn , "VPSHFTCH03" );
							if ( msgType.equalsIgnoreCase("E"))
							{
								break;
							}
						}
					} // End of  fromDate
					else if(childNodeName.equalsIgnoreCase("to_dt")) // Validation for role_code
					{
						toDate = checkNull(genericUtility.getColumnValue("to_dt", curDom));
						
						if(toDate == null || toDate.trim().length() == 0)
						{
							errCode = "VPSHFTCH04";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
							msgType =  errorType(conn , "VPSHFTCH04" );
							if ( msgType.equalsIgnoreCase("E"))
							{
								break;
							}
						}
						else
						{
							todt =  sdf.parse(toDate);
							frdt  = sdf.parse(fromDate);
							if(frdt.compareTo(todt)>0)
							{
								errCode = "VPSHFTCH05";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
								msgType =  errorType(conn , "VPSHFTCH05" );
								if ( msgType.equalsIgnoreCase("E"))
								{
									break;
								}
							}
							
						}
					} // End of  toDate
					
				}
				 break;
				 
			case 2:
				parentNodeList = curDom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
			
				for(ctr = 0; ctr < childNodeListLength; ctr ++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase("shift") )     // Validation for emp code 
					{
						shift = checkNull(genericUtility.getColumnValue("shift", curDom));
						if(shift == null || shift.trim().length() == 0)
						{
							errCode = "VPSHFTCH06";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
							msgType =  errorType(conn , "VPSHFTCH06" );
							if ( msgType.equalsIgnoreCase("E"))
							{
								break;
							}
						}
						else
						{
							flag = isRecordExist(conn," WORKSHFT "," WHERE SHIFT ='"+shift+"'");

							if(flag == false)
							{
								errCode = "VPSHFTCH07";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());

								msgType =  errorType(conn , "VPSHFTCH07" );
								if ( msgType.equalsIgnoreCase("E"))
								{
									break;
								}
							}
							
						}
						
					}   //shift end
					
					
				}
				 break;
			
			}
			int errListSize = errList.size();
			count = 0;
			String errFldName = null;
			AppConnectParm appConnect = new AppConnectParm();
			InitialContext ctx = new InitialContext(appConnect.getProperty()) ;
			ITMDBAccessLocal itmDBAccessEJB = (ITMDBAccessLocal)ctx.lookup("ibase/ITMDBAccessEJB/local");			
			
			if(errList != null && errListSize > 0)
			{
				for(count = 0; count < errListSize; count ++)
				{
					errCode = errList.get(count);
					errFldName = errFields.get(count);
					System.out.println("errCode .........." + errCode);
					errString = itmDBAccessEJB.getErrorString(errFldName, errCode, userId);
					System.out.println("errString........"+errString);
					
					errString = itmDBAccessEJB.getErrorString("", errCode, userId);
					System.out.println("errString........"+errString);
					
					errorType = errorType(conn , errCode);
					return errString;
					
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;
				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}
		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				
				if(rs != null) 
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null) 
				{
					pstmt.close();
					pstmt = null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}
				
			} 
			catch(Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		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 = "";
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("In wfValData Current xmlString="+xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("In wfValData Header xmlString1="+xmlString1);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
				System.out.println("In wfValData All xmlString2="+xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
			
	        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("[ShiftChangeIc][itemChanged(Document,Document,String,string,editflag)] :==>\n");

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = new StringBuffer();

		NodeList parentNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		NodeList childNodeList = null;

		String empName = ""; 
		String shift = ""; 
		String descr = ""; 
		String sql = "";


		String childNodeName = "";
		String curtranid = "";
		String columnValue = "";

		int childNodeListLength=0;
		int ctr = 0;
		int currentFormNo = 0;

		String siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
		String empCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");

		try
		{
				
			System.out.println("**empCode**"+empCode);
			
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");		
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			System.out.println("[ShiftChangeIc] [itemChanged] :currentFormNo ....." +currentFormNo);
			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");

			switch (currentFormNo)
			{
				case 1:						
					parentNodeList = dom1.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					childNodeListLength = childNodeList.getLength();
					// valueXmlString.append("<Detail1>\r\n");
					valueXmlString.append("<Detail>\r\n");
					/*
					if (currentColumn.trim().equalsIgnoreCase("itm_default"))
					{ 
						
						sql="SELECT TRIM(EMP_FNAME) || ' ' || (CASE WHEN EMP_MNAME IS NOT NULL THEN TRIM(EMP_MNAME) ELSE '' END) || ' ' || TRIM(EMP_LNAME) AS EMP_NAME FROM EMPLOYEE  WHERE  EMP_CODE = ? ";
						pstmt =conn.prepareStatement(sql);
						pstmt.setString(1, checkNull(empCode));
						System.out.println("Emp Name SQL" + sql);
						rs = pstmt.executeQuery();
						while (rs.next())
						{
							empName=rs.getString("EMP_NAME");
						}
						closePstmtRset(pstmt, rs);
						
						valueXmlString.append("<emp_code><![CDATA[").append(empCode).append("]]></emp_code>");
						valueXmlString.append("<emp_name><![CDATA[").append(empName).append("]]></emp_name>");
					
					}
					else if(currentColumn.equalsIgnoreCase("emp_code"))  
					*/
					if(currentColumn.equalsIgnoreCase("emp_code"))  
					{	
						empCode = checkNull(genericUtility.getColumnValue("emp_code", dom));

						if(empCode != null && empCode.trim().length() > 0)
						{
							sql="SELECT TRIM(EMP_FNAME) || ' ' || (CASE WHEN EMP_MNAME IS NOT NULL THEN TRIM(EMP_MNAME) ELSE '' END) || ' ' || TRIM(EMP_LNAME) AS EMP_NAME FROM EMPLOYEE  WHERE  EMP_CODE = ? ";
							pstmt =conn.prepareStatement(sql);
							pstmt.setString(1, empCode);
							System.out.println("Emp Name SQL" + sql);
							rs = pstmt.executeQuery();
							while (rs.next())
							{
								empName=rs.getString("EMP_NAME");
							}
							closePstmtRset(pstmt, rs);
							System.out.println("Emp  name :="+empName);
							
							valueXmlString.append("<emp_code><![CDATA[").append(empCode).append("]]></emp_code>");
							valueXmlString.append("<emp_name><![CDATA[").append(empName).append("]]></emp_name>");  
						}
						else
						{
							 valueXmlString.append("<emp_name><![CDATA[").append("<![CDATA[]]>").append("]]></emp_name>\r\n");

						}//end of empCode item change
					}
						
					//valueXmlString.append("</Detail1>\r\n");	
					valueXmlString.append("</Detail>\r\n");	
					System.out.println("xml string ****** "+valueXmlString.toString());
					break;
	   				
					case 2 :
						/* Searching the dom for the incoming column value start*/
						parentNodeList = dom.getElementsByTagName("Detail2");
						parentNode = parentNodeList.item(0);
						childNodeList = parentNode.getChildNodes();
						ctr = 0;
						childNodeListLength = childNodeList.getLength();
						//valueXmlString.append("<Detail2>\r\n");
						valueXmlString.append("<Detail1>\r\n");
						
						if(currentColumn.trim().equalsIgnoreCase("shift"))  //Item change for emp_code
						{	
							shift = checkNull(genericUtility.getColumnValue("shift", dom));
							if(shift != null && shift.trim().length() > 0)
							{
								 sql="SELECT DESCR  FROM WORKSHFT  WHERE SHIFT = ? ";
								 pstmt =conn.prepareStatement(sql);
								 pstmt.setString(1, shift);
								 System.out.println("Emp shift SQL" + sql);
								 rs = pstmt.executeQuery();
								while (rs.next())
								{
									descr = rs.getString("DESCR");
								}
								closePstmtRset(pstmt, rs);
								System.out.println("shift  ::: :="+descr);
								
								valueXmlString.append("<workshft_descr><![CDATA[").append(checkNull(descr)).append("]]></workshft_descr>");
							}
							else
							{
								valueXmlString.append("<workshft_descr><![CDATA[").append(checkNull(descr)).append("]]></workshft_descr>");

									
							}//end of empCode item change
						}
						
	        			//valueXmlString.append("</Detail2>\r\n");	
	        			valueXmlString.append("</Detail1>\r\n");	
						break;
	 			} //eof switch
				valueXmlString.append("</Root>\r\n");	
			} //eof try
			catch(Exception e)
			{
				System.out.println("Exception :[ShiftChangeIc][itemChanged] BEFORE finally==>\n"+e.getMessage());
				throw new ITMException(e);
			}
			finally
			{
				try
				{   
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					System.out.println("finally pstmt Closed.......");
					}
					if(rs != null)
					{
						rs.close();
						rs = null;
						System.out.println("finally rs Closed.......");
					}
					if(conn != null)
					{
						conn.close();
						conn = null;
						System.out.println("finally Connection Closed.......");
					}
				}
				catch(SQLException e)
				{
					System.out.println("Exception :[ShiftChangeIc][itemChanged::finally] :==>\n"+e.getMessage());
					e.printStackTrace();
					throw new ITMException(e);
				}
			}		
			System.out.println("value returned is last ****************************   "+ valueXmlString.toString());
			return valueXmlString.toString();
		}

		private boolean isRecordExist(Connection conn , String tableName, String condition)
		{
		
			PreparedStatement pstmt = null ; 
			ResultSet rs = null;
			String sql="";
			boolean isExist=false;
			int recCount=0;
			
			
			try
			{	
				
				sql = " SELECT  COUNT(*)  FROM  "+tableName +"  "+condition;
				pstmt =  conn.prepareStatement(sql);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					recCount=rs.getInt(1);
				
				}
				if(recCount>0)
				{
					isExist=true;
					
				}
				else
				{
					isExist=false;
				
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}		
			finally
			{
				try
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}		
			
			System.out.print("---------Final--isExist-------"+isExist);
			return isExist;
		}
		
		private String checkNull(String input)
		{
			if (input == null) 
			{
				input = "";
			} 
			else
			{
				input = input.trim();
			}
			return input;
		}
		private String errorType(Connection conn , String errorCode)
		{
			String msgType = "";
			PreparedStatement pstmt = null ; 
			ResultSet rs = null;
			try
			{			
				String  sql = "SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO = ?";
				pstmt = conn.prepareStatement(sql);			
				pstmt.setString(1,errorCode);			
				rs = pstmt.executeQuery();
				while(rs.next())
				{
					msgType = rs.getString("MSG_TYPE");
				}		
				
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}		
			finally
			{
				try
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
			}		
			return msgType;
		}
		private void closePstmtRset(PreparedStatement pstmt, ResultSet rset )throws Exception
		{
			System.out.println("Closing PreparedStatement and result.........");
			try 
			{
				if (rset != null)
				{
					rset.close();
					rset = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			
			}
			catch (Exception exp) 
			{
				exp.printStackTrace();
				throw new Exception(exp);
			}
		}		
	
		
}
/*Created by Chetna on [25/08/2014] For Shift Rotate Change [END]
 * */