/* Developed By Vallabh Kadam
 * Date : 30-NOV-2016
 * Component Name : EmpStatusDateChgIC
 */
package ibase.webitm.ejb.adm;

import ibase.system.config.ConnDriver;
import ibase.utility.E12GenericUtility;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.adm.adv.EmpMaritalStatusConfLocal;
import ibase.webitm.utility.ITMException;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

@Stateless
public class EmpStatusDateChgIC extends ValidatorEJB implements EmpStatusDateChgICLocal , EmpStatusDateChgICRemote
{
	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 = "";
		E12GenericUtility genericUtility = new E12GenericUtility();
		try
		{
			System.out.println("EmpMaritalStatusConfIC:wfValData value of xmlString ["+xmlString+"]");
			System.out.println("EmpMaritalStatusConfIC:wfValData value of xmlString ["+xmlString1+"]");
			System.out.println("EmpMaritalStatusConfIC:wfValData value of xmlString ["+xmlString2+"]");

			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 = checkNull(wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams));
			System.out.println ("EmpMaritalStatusConfIC:ErrString: " + errString);
		}
		catch (Exception e)
		{
			System.out.println ("Exception: EmpMaritalStatusConfIC: wfValData(String xmlString): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println ("Returning from EmpMaritalStatusConfIC wfValData");
		return errString;  
	}

	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		java.sql.Timestamp tranDate = null,tranDateTemp=null;
		NodeList parentList = null , childList = null;
		Node parentNode = null , childNode = null ;
		int noOfChilds = 0 , counterChild = 0;
		String sql = "", empCode = "", confirm = "", errString = "", tranDateStr = "",statusDateStr="";
		String childNodeName = "";
		int currentFormNo = 0;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		E12GenericUtility genericUtility = new E12GenericUtility();
		boolean latestTran=true;
		
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("Driver");

			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();
				switch(currentFormNo)
				{
					case 1:
					System.out.println("In case 1 ::::::::");
					empCode =  genericUtility.getColumnValue("emp_code", dom);
					System.out.println("empCode from Dom::"+empCode);
					tranDateStr = genericUtility.getColumnValue("tran_date", dom);
					statusDateStr = genericUtility.getColumnValue("status_date", dom);
					System.out.println("tranDateStr from Dom::"+tranDateStr);
					tranDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(tranDateStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
					System.out.println("tranDate after parsing::"+tranDate);
									
					if(statusDateStr==null || statusDateStr.trim().length()==0)
					{
						errString = itmDBAccessEJB.getErrorString("","VTSTDTBLNK","","",conn);
						return errString;
					}
					
					/**
					 * Select all tran date
					 * */
					ArrayList<Timestamp> tranDateAll=new ArrayList<Timestamp>();
					sql = "SELECT TRAN_DATE FROM EMP_MARITALCHG WHERE EMP_CODE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, empCode);
					rs = pstmt.executeQuery();
					while(rs.next())
					{
						tranDateTemp = rs.getTimestamp("TRAN_DATE");
						tranDateAll.add(tranDateTemp);
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					
					for(Timestamp tempDate:tranDateAll)
					{
						if(tranDate.before(tempDate))
						{
							latestTran=false;
							break;
						}
					}
					
					/**
					 * Check Transaction is latest
					 * */
					if(!latestTran)
					{
						System.out.println("@V@ Transaction is OLD ..");
						errString = itmDBAccessEJB.getErrorString("", "VTOLDTRAN", "", "", conn);
						return errString;
					}
					
					sql = "SELECT CONFIRM FROM EMP_MARITALCHG WHERE EMP_CODE = ? AND TRAN_DATE = ?";
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, empCode);
					pstmt.setTimestamp(2, tranDate);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						confirm = checkNull(rs.getString("CONFIRM"));				
					}
					pstmt.close();
					pstmt=null;
					rs.close();
					rs=null;
					System.out.println("@V@ VALLABH confirm :- ["+confirm+"]");
					if("X".equalsIgnoreCase(confirm))
					{
						errString = itmDBAccessEJB.getErrorString("", "VTALRDCACL", "", "", conn);
						return errString;
					}
				}
			}
		}
		catch(Exception e)
		{
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally 
		{
			try 
			{
				close(pstmt, rs);
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			} 
			catch (Exception e)
			{
				e.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 errString = null;
		E12GenericUtility genericUtility = new E12GenericUtility();
		try
		{
			System.out.println("EmpMaritalStatusConfIC:itemChanged value of xmlString ["+xmlString+"]");
			System.out.println("EmpMaritalStatusConfIC:itemChanged value of xmlString ["+xmlString1+"]");
			System.out.println("EmpMaritalStatusConfIC:itemChanged value of xmlString ["+xmlString2+"]");
			System.out.println("objContext ..:: ["+objContext+"]");
			System.out.println("currentColumn ..:: ["+currentColumn+"]");
			System.out.println("editFlag ..:: ["+editFlag+"]");

			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 = itemChanged(dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams);
			System.out.println ("EmpMaritalStatusConfIC::ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ("EmpMaritalStatusConfIC::Exception :itemChanged(String,String):" + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		System.out.println ("EmpMaritalStatusConfIC::returning from itemChanged");
		return errString;
	}

	public String itemChanged(Document dom, Document dom1, Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		int currentFormNo = 0;

		StringBuffer valueXmlString = null;
		String objNameDefault = "" ;
		String sql = "", empCode = "", oldStatus = "", newStatus = "", empName = "", confirm = "", tranDateStr = "", statusDateStr = "";
		double amount = 0.0d;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Timestamp tranDate = null;
		Date statusDate = null;
		String prdCode = "", giftCode = "";
		String empCodeAprv="",spouseName="",empFname="",empMname="",empLname="",shortName="",voucherNo="",
				empFnameO="",empMnameO="",empLnameO="",shortNameO="";
		AdmCommon admCommon = null;
		SimpleDateFormat sdf = null;
		try
		{
			sdf = new SimpleDateFormat(getApplDateFormat());
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("Driver");
			E12GenericUtility genericUtility = new E12GenericUtility();

			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>");
			objNameDefault  = checkNull(getObjName(dom ,"1"));
			System.out.println("objNameDefault ..:: ["+objNameDefault+"]");

			switch (currentFormNo)
			{
				case 1:	
				{
					System.out.println("current form::::::::::::"+currentFormNo);
					empCode =  genericUtility.getColumnValue("emp_code", dom);
					System.out.println("empCode from Dom::"+empCode);
					tranDateStr = genericUtility.getColumnValue("tran_date", dom);
					System.out.println("tranDateStr from Dom::"+tranDateStr);
					tranDate = java.sql.Timestamp.valueOf(genericUtility.getValidDateTimeString(tranDateStr, genericUtility.getApplDateFormat(),genericUtility.getDBDateFormat()));
					System.out.println("tranDate after parsing::"+tranDate);
					statusDateStr = genericUtility.getColumnValue("status_date", dom);
	
					valueXmlString.append("<Detail>\r\n");
					if(currentColumn.equalsIgnoreCase("itm_defaultedit"))
					{
						System.out.println("@V@ In itm_defaultedit");
						
						sql = "SELECT STATUS_DATE, OLD_STATUS, NEW_STATUS, SHORT_NAME, CONFIRM,EMP_CODE__APRV," +
								" SPOUSE_NAME,EMP_FNAME,EMP_MNAME,EMP_LNAME,SHORT_NAME,VOUCHER_NO,AMOUNT," +
								" EMP_FNAME__O,EMP_MNAME__O,EMP_LNAME__O,SHORT_NAME__O" +
								" FROM EMP_MARITALCHG" +
								" WHERE EMP_CODE = ? AND TRAN_DATE = ? ";
						pstmt=conn.prepareStatement(sql);
						pstmt.setString(1, empCode);
						pstmt.setTimestamp(2, tranDate);
						rs=pstmt.executeQuery();
						while(rs.next())
						{							
							statusDate = rs.getDate("STATUS_DATE");
							oldStatus=checkNull(rs.getString("OLD_STATUS"));
							newStatus = checkNull(rs.getString("NEW_STATUS"));
							empName = checkNull(rs.getString("SHORT_NAME"));
							confirm = checkNull(rs.getString("CONFIRM"));
							empCodeAprv = checkNull(rs.getString("EMP_CODE__APRV"));
							spouseName = checkNull(rs.getString("SPOUSE_NAME"));
							empFname = checkNull(rs.getString("EMP_FNAME"));
							empMname = checkNull(rs.getString("EMP_MNAME"));
							empLname = checkNull(rs.getString("EMP_LNAME"));
							shortName = checkNull(rs.getString("SHORT_NAME"));
							voucherNo = checkNull(rs.getString("VOUCHER_NO"));
							amount = rs.getDouble("AMOUNT");
							empFnameO = checkNull(rs.getString("EMP_FNAME__O"));
							empMnameO = checkNull(rs.getString("EMP_MNAME__O"));
							empLnameO = checkNull(rs.getString("EMP_LNAME__O"));
							shortNameO = checkNull(rs.getString("SHORT_NAME__O"));
						}
						close(pstmt, rs);
						
						valueXmlString.append("<emp_code protect=\"1\"><![CDATA[" + empCode + "]]></emp_code>\r\n");
						valueXmlString.append("<tran_date protect=\"1\"><![CDATA[" + tranDateStr + "]]></tran_date>\r\n");
						valueXmlString.append("<status_date><![CDATA[" + statusDateStr + "]]></status_date>\r\n");
						valueXmlString.append("<old_status protect=\"1\"><![CDATA[" + oldStatus + "]]></old_status>\r\n");
						valueXmlString.append("<new_status protect=\"1\"><![CDATA[" + newStatus + "]]></new_status>\r\n");
						valueXmlString.append("<emp_code__aprv protect=\"1\"><![CDATA[" + empCodeAprv + "]]></emp_code__aprv>\r\n");
						valueXmlString.append("<spouse_name protect=\"1\"><![CDATA[" + spouseName + "]]></spouse_name>\r\n");
						valueXmlString.append("<emp_fname protect=\"1\"><![CDATA[" + empFname + "]]></emp_fname>\r\n");
						valueXmlString.append("<emp_mname protect=\"1\"><![CDATA[" + empMname + "]]></emp_mname>\r\n");
						valueXmlString.append("<emp_lname protect=\"1\"><![CDATA[" + empLname + "]]></emp_lname>\r\n");
						valueXmlString.append("<short_name protect=\"1\"><![CDATA[" + shortName + "]]></short_name>\r\n");
						valueXmlString.append("<voucher_no protect=\"1\"><![CDATA[" + voucherNo + "]]></voucher_no>\r\n");
						valueXmlString.append("<amount protect=\"1\"><![CDATA[" + amount + "]]></amount>\r\n");
						valueXmlString.append("<emp_fname__o protect=\"1\"><![CDATA[" + empFnameO + "]]></emp_fname__o>\r\n");
						valueXmlString.append("<emp_mname__o protect=\"1\"><![CDATA[" + empMnameO + "]]></emp_mname__o>\r\n");
						valueXmlString.append("<emp_lname__o protect=\"1\"><![CDATA[" + empLnameO + "]]></emp_lname__o>\r\n");
						valueXmlString.append("<short_name__o protect=\"1\"><![CDATA[" + shortNameO + "]]></short_name__o>\r\n");
					}
					valueXmlString.append ("</Detail>\r\n");
				}
				break;
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		finally 
		{
			try 
			{
				close(pstmt, rs);
				if (conn != null)
				{
					conn.close();
					conn = null;
				}

			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		valueXmlString.append("</Root>\r\n");
		System.out.println("valueXmlString"+valueXmlString);
		return valueXmlString.toString();
	}
	private String getObjName(Document dom,String objContext)
	{
		Node elementName = null;
		NodeList elementList = null;
		String objName = "";

		try
		{
			elementList = dom.getElementsByTagName("Detail"+objContext);
			elementName = elementList.item(0);
	
			if(elementName != null && ("Detail"+objContext).equalsIgnoreCase(elementName.getNodeName()))
			{
				NamedNodeMap etlAttributes = elementName.getAttributes();
	
				if(etlAttributes != null)
				{
					if(etlAttributes.getNamedItem("obj_name") != null)
					{
						objName = etlAttributes.getNamedItem("obj_name").getNodeValue();
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return objName;
	}
	
	private String checkNull(String input)
	{
		if(input == null)
		{
			input = "";
		}

		else 
		{
			input = input.trim();
		}
		return input;
	}
	
	private void close(PreparedStatement pstmt,ResultSet rs) //Method to close PreparedStatement & ResultSet
	{
		try
		{
			if( rs != null)
			{
				rs.close();
				rs = null;
			}
			if( pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}