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.xml.parsers.*;
import javax.ejb.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.TransIDGenerator;//TID
import ibase.utility.CommonConstants;//TID
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3
public class PayRollVouc extends ValidatorEJB implements PayRollVoucLocal,PayRollVoucRemote	//SessionBean
{
	Connection conn = null;
	PreparedStatement pstmt=null;
	ResultSet rs = null;
	String sql=null;
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	GenericUtility genericUtility = GenericUtility.getInstance();
	//Some Global Variable
	String userId = null;
	String empCodeAprv= null;
	String loginSite = null;
	/*
	public void ejbCreate() throws RemoteException, CreateException{System.out.println("PayRollVoucEJB  ...........................");}
	public void ejbRemove(){}
	public void ejbActivate(){}
	public void ejbPassivate(){}
	*/
	public String wfValData() throws RemoteException,ITMException{return "";}
	public String itemChanged() throws RemoteException,ITMException{return "";}
	//ItemChange 
	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
		{
		
			System.out.println("xmlString:::" + xmlString);
			System.out.println("xmlString1:::" + xmlString1);
			System.out.println("xmlString2:::" + xmlString2);
			dom1 = parseString(xmlString1); 
			dom = parseString(xmlString); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [PayRollVoucEJB][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("Item Changes Call..................");
		NodeList parentNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		NodeList childNodeList = null;
		userId = getValueFromXTRA_PARAMS(xtraParams,"userId");
		empCodeAprv= getValueFromXTRA_PARAMS(xtraParams,"loginEmpCode");
		loginSite = getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
		
//		StringBuffer retString = new StringBuffer();
		StringBuffer valueXmlString = new StringBuffer();
		
		
		int n;
		int currentFormNo = 0;
		int ctr = 0;
		String errCode = "";
		String errString = "";
		String sql = "";
		String columnValue = "";
		String childNodeName = "";
		
		System.out.println("xtraParams::::::::::::::::"+xtraParams);
		try
		{
			if(conn == null)
			{ 
				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>");
			System.out.println("Form No:::"+currentFormNo);							
			switch (currentFormNo)
			{
				case 1:
//	     			SEARCHING THE DOM FOR THE INCOMING COLUMN VALUE START
					parentNodeList = dom.getElementsByTagName("Detail1");
					parentNode = parentNodeList.item(0);
					childNodeList = parentNode.getChildNodes();
					ctr = 0;
					int childNodeListLength = childNodeList.getLength();
					do
					{
						childNode = childNodeList.item(ctr);
						childNodeName = childNode.getNodeName();
						if(childNodeName.equals(currentColumn))
						{
							if (childNode.getFirstChild() != null)
							{
								columnValue=childNode.getFirstChild().getNodeValue().trim();
							}
						}
						ctr++;
					}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));
					System.out.println("current column="+currentColumn);
					valueXmlString.append("<Detail1>");	
					if (currentColumn.trim().equalsIgnoreCase("itm_default"))
					{
						java.sql.Timestamp toDate = null;
						java.sql.Timestamp currDate = null;
						currDate = new java.sql.Timestamp(System.currentTimeMillis()) ;
						String dateAf =null;
						
						String mprdCode = null;
						String siteDescr=null;
						sql = "SELECT PRD_CODE  FROM PARAMETER";
						System.out.println("Parameter Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							mprdCode = rs.getString(1);
							System.out.println("Period Code From Parameters ["+mprdCode+"]");
						}
						
						rs.close();
						pstmt.close();
						if(mprdCode!=null)
						{
							sql = "SELECT TO_DATE  FROM PERIOD WHERE CODE = '"+mprdCode+"'";
							System.out.println("period Query:::"+sql);
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								toDate = rs.getTimestamp(1);
								System.out.println("To Date From Period["+toDate+"]");
							}
							rs.close();
							pstmt.close();
						}
						
						if(toDate==null)toDate = currDate;
						if(toDate!=null)
						{
							if(toDate.compareTo(currDate)<=0)
							{
								System.out.println("Date From period["+toDate+"]");
								System.out.println("CurrentDate["+currDate+"]");
								toDate = currDate;
							}
						}
						dateAf = getCurrdateAppFormat(toDate);
						sql = 	" SELECT DESCR  FROM SITE WHERE SITE_CODE = '"+loginSite+"'";
						System.out.println("Site Descr Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							siteDescr = rs.getString(1);
						}
						rs.close();
						pstmt.close();
						//****************
						String prdDescr = null;
						if(mprdCode!=null)
						{
							
							sql ="SELECT DESCR FROM PERIOD WHERE CODE = '"+mprdCode.trim()+"'";;
							System.out.println("period Descr Name Query:::"+sql);
							pstmt = conn.prepareStatement(sql);
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								prdDescr = (rs.getString(1)==null?" ":rs.getString(1));
							}
						
							rs.close();
							pstmt.close();
						}
						
						//*****************
						valueXmlString.append("<fr_prd_descr>").append(prdDescr).append("</fr_prd_descr>\r\n");
						valueXmlString.append("<to_prd_descr>").append(prdDescr).append("</to_prd_descr>\r\n");
						valueXmlString.append("<site_code__fr>").append(loginSite).append("</site_code__fr>\r\n");
						valueXmlString.append("<site_code__to>").append(loginSite).append("</site_code__to>\r\n");
						valueXmlString.append("<payroll_date>").append(dateAf).append("</payroll_date>\r\n");
						valueXmlString.append("<prd_code__fr>").append(mprdCode).append("</prd_code__fr>\r\n");
						valueXmlString.append("<prd_code__to>").append(mprdCode).append("</prd_code__to>\r\n");
						valueXmlString.append("<fr_site_descr>").append(siteDescr).append("</fr_site_descr>\r\n");
						valueXmlString.append("<to_site_descr>").append(siteDescr).append("</to_site_descr>\r\n");
						valueXmlString.append("</Detail1>\r\n");										
						
					}
					
					else if (currentColumn.trim().equalsIgnoreCase("emp_code__fr") ||currentColumn.trim().equalsIgnoreCase("emp_code__to")  )
					{
						String FName=" ";
						String LName = "  ";
						String FullName =null;
						
						sql = "SELECT EMP_FNAME, EMP_LNAME FROM EMPLOYEE WHERE EMP_CODE = '"+columnValue.trim()+"'";;
						System.out.println("Emp Name Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							FName = (rs.getString(1)==null?"  ":rs.getString(1));
							LName =(rs.getString(2)==null?"  ":rs.getString(2));
						}
						FullName = FName + " " + LName;
						rs.close();
						pstmt.close();
						if(currentColumn.trim().equalsIgnoreCase("emp_code__fr"))
						{
							valueXmlString.append("<emp_name__fr>").append(FullName).append("</emp_name__fr>\r\n");
							
						}
						if(currentColumn.trim().equalsIgnoreCase("emp_code__to"))
						{
							valueXmlString.append("<emp_name__to>").append(FullName).append("</emp_name__to>\r\n");
							
						}
				
    					valueXmlString.append("</Detail1>\r\n");
					}
					else if (currentColumn.trim().equalsIgnoreCase("prd_code__fr") ||currentColumn.trim().equalsIgnoreCase("prd_code__to")  )
					{
						String prdDescr = null;
						sql ="SELECT DESCR FROM PERIOD WHERE CODE = '"+columnValue.trim()+"'";;
						System.out.println("period Descr Name Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							prdDescr = (rs.getString(1)==null?" ":rs.getString(1));
						}
						
						rs.close();
						pstmt.close();
						if(currentColumn.trim().equalsIgnoreCase("prd_code__fr"))
						{
							valueXmlString.append("<fr_prd_descr>").append(prdDescr).append("</fr_prd_descr>\r\n");
							
						}
						if(currentColumn.trim().equalsIgnoreCase("prd_code__to"))
						{
							valueXmlString.append("<to_prd_descr>").append(prdDescr).append("</to_prd_descr>\r\n");
							
						}
				
    					valueXmlString.append("</Detail1>\r\n");
					}
					else if (currentColumn.trim().equalsIgnoreCase("site_code__fr") ||currentColumn.trim().equalsIgnoreCase("site_code__to")  )
					{
						String siteDescr = null;
						sql ="SELECT DESCR FROM SITE WHERE SITE_CODE = '"+columnValue.trim()+"'";
						System.out.println("Site descr Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							siteDescr =(rs.getString(1)==null?" ":rs.getString(1));
						}
						
						rs.close();
						pstmt.close();
						if(currentColumn.trim().equalsIgnoreCase("site_code__fr"))
						{
							valueXmlString.append("<fr_site_descr>").append(siteDescr).append("</fr_site_descr>\r\n");
							
						}
						if(currentColumn.trim().equalsIgnoreCase("site_code__to"))
						{
							valueXmlString.append("<to_site_descr>").append(siteDescr).append("</to_site_descr>\r\n");
							
						}
				
    					valueXmlString.append("</Detail1>\r\n");
					}
					else if (currentColumn.trim().equalsIgnoreCase("proc_group__fr") ||currentColumn.trim().equalsIgnoreCase("proc_group__to")  )
					{
						String procGroupDescr = null;
						sql ="	SELECT DESCR   FROM GENCODES WHERE FLD_NAME='PROC_GROUP' AND FLD_VALUE = '"+columnValue.trim()+"'";
						System.out.println("PROC_GROUP  Query:::"+sql);
						pstmt = conn.prepareStatement(sql);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							procGroupDescr =(rs.getString(1)==null?" ":rs.getString(1));
						}
						
						rs.close();
						pstmt.close();
						if(currentColumn.trim().equalsIgnoreCase("proc_group__fr"))
						{
							valueXmlString.append("<proc_group__fr_name>").append(procGroupDescr).append("</proc_group__fr_name>\r\n");
							
						}
						if(currentColumn.trim().equalsIgnoreCase("proc_group__to"))
						{
							valueXmlString.append("<proc_group__to_name>").append(procGroupDescr).append("</proc_group__to_name>\r\n");
							
						}
				
    					valueXmlString.append("</Detail1>\r\n");
					}
					break;
					case 2:
					//valueXmlString.append("</Detail>");
					//break;
				}//END OF SWITCH
				valueXmlString.append("</Root>");	
				System.out.println("valueXmlString[sepclose]"+valueXmlString);
			}//END OF TRY
		
		catch(Exception e)
		{
			System.out.println("Exception ::"+e.getMessage());
			e.printStackTrace();
		} 
		return valueXmlString.toString();
	}//END OF ITEMCHNGE
	//Validation


	private  String getCurrdateAppFormat(java.sql.Timestamp ts)
	{
		String dateAf ="";
		System.out.println("Comming Date[In DB Format] :::"+ts.toString());
		try
		{
				Object date = null;
				SimpleDateFormat sdf = new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = sdf.parse(ts.toString());
				dateAf = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(date).toString();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("Retturning Date :::"+dateAf);
		return (dateAf);
	}
	
}//end of ejb