/* Developed By Ahmed Mohammed Ali
 * Date : 20-JUL-2016
 * Component Name : EmpMaritalStatusConfIC
 */
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.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.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 EmpMaritalStatusConfIC extends ValidatorEJB implements EmpMaritalStatusConfICLocal , EmpMaritalStatusConfICRemote
{
	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;
		NodeList parentList = null , childList = null;
		Node parentNode = null , childNode = null ;
		int noOfChilds = 0 , counterChild = 0;
		String sql = "", empCode = "", confirm = "", errString = "", tranDateStr = "";
		String childNodeName = "";
		int currentFormNo = 0;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		E12GenericUtility genericUtility = new E12GenericUtility();
		
		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);
				if (childNode.getNodeType() != Node.ELEMENT_NODE) 
				{
					continue;
				}
				childNodeName = childNode.getNodeName();
				System.out.println("childNodeName.editFlag." + childNodeName + ".." + editFlag);
				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);
					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("emp_code".equalsIgnoreCase(childNodeName))
					{
						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();
						while(rs.next())
						{
							confirm = checkNull( rs.getString( "CONFIRM" ) );
						}
						close(pstmt, rs);
						if( "Y".equalsIgnoreCase(confirm.trim()) )
						{
							errString = itmDBAccessEJB.getErrorString("","VTMARSCH01","","",conn);
							return errString;
						}
					}
					else if("generate_voucher".equalsIgnoreCase(childNodeName))
					{
						String genVoucher =  genericUtility.getColumnValue("generate_voucher", dom);
						if(genVoucher == null || genVoucher.trim().length() == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","VTMARSCH04","","",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 = "";
		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);
	
					valueXmlString.append("<Detail>\r\n");
					if(currentColumn.equalsIgnoreCase("itm_default"))
					{
						sql = "SELECT STATUS_DATE, OLD_STATUS, NEW_STATUS, SHORT_NAME, 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();
						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"));
						}
						close(pstmt, rs);
						
						if(statusDate != null)
						{
							statusDateStr = sdf.format(statusDate);
						}
						
						sql = "SELECT CODE FROM PERIOD WHERE ? BETWEEN FR_DATE AND TO_DATE";
						pstmt = conn.prepareStatement(sql);
						pstmt.setTimestamp(1, tranDate);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							prdCode = checkNull(rs.getString("CODE"));
						}
						close(pstmt, rs);
						
						admCommon = new AdmCommon();
						giftCode = admCommon.getEnv("999999", "GIFT_CODE", conn);
						if("NULLFOUND".equalsIgnoreCase(giftCode))
						{
							giftCode = "";
						}
						System.out.println("giftCode ::" + giftCode);
						
						sql = "SELECT NVL(AMOUNT,0) AS TOTAL_AMOUNT FROM PAYROLL_PROJDET WHERE EMP_CODE = ? AND PRD_CODE = ? AND AD_CODE = ?";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, empCode);
						pstmt.setString(2, prdCode);
						pstmt.setString(3, giftCode);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							amount = rs.getDouble("TOTAL_AMOUNT");
						}
						close(pstmt, rs);
						
						valueXmlString.append("<emp_code><![CDATA[" + empCode + "]]></emp_code>\r\n");
						valueXmlString.append("<tran_date><![CDATA[" + tranDateStr + "]]></tran_date>\r\n");
						valueXmlString.append("<status_date><![CDATA[" + statusDateStr + "]]></status_date>\r\n");
						valueXmlString.append("<old_status><![CDATA[" + oldStatus + "]]></old_status>\r\n");
						valueXmlString.append("<new_status><![CDATA[" + newStatus + "]]></new_status>\r\n");
						valueXmlString.append("<emp_name><![CDATA[" + empName + "]]></emp_name>\r\n");
						
						//if(!("Y".equalsIgnoreCase(confirm)))
						if(!("Y".equalsIgnoreCase(confirm)) && !("X".equalsIgnoreCase(confirm)))//Modified by Ahmed on 19-Jun-2017 to set blank value in dropdown
						{
							if("M".equalsIgnoreCase(newStatus.trim()))
							{
								valueXmlString.append("<gift_amount><![CDATA[" + amount + "]]></gift_amount>\r\n");
								//valueXmlString.append("<generate_voucher protect=\"0\"><![CDATA[N]]></generate_voucher>\r\n");
								valueXmlString.append("<generate_voucher protect=\"0\"><![CDATA[]]></generate_voucher>\r\n");//Modified by Ahmed on 19-Jun-2017 to set blank value in dropdown 
							}
							else
							{
								valueXmlString.append("<gift_amount><![CDATA[0]]></gift_amount>\r\n");
								valueXmlString.append("<generate_voucher protect=\"1\"><![CDATA[N]]></generate_voucher>\r\n");
							}
						}
						else
						{
							
							valueXmlString.append("<gift_amount><![CDATA[" +amount+ "]]></gift_amount>\r\n");
							valueXmlString.append("<generate_voucher protect=\"1\"><![CDATA[N]]></generate_voucher>\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();
		}
	}
}