package ibase.webitm.ejb.adm;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.sql.Timestamp;
import org.w3c.dom.Document;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList; 
import javax.ejb.Stateless;


@Stateless 
public class EmpBondAmount extends ValidatorEJB implements EmpBondAmountLocal,EmpBondAmountRemote
{
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}

	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("IN WF VAL DATA ------------>>");
		String errString = null;
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = "";
	
		System.out.println("\n\n xmlString in wfValData \n:" + xmlString + "\n");
		System.out.println("\n\n xmlString1 in wfValData \n :" + xmlString1 +"\n");
		System.out.println("\n\n xmlString2 in wfValData \n :" + xmlString2 +"\n");
	
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0)
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			//ADDED FOR INVOIKING VALIDATION IN WORKFLOW

			// Modified by Rahul on 21/07/2015 [To avoid unwanted coding and confusion].Start

			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);

			/*
			if( objContext != null && Integer.parseInt(objContext) == 1 )
			{
				parentNodeList = dom2.getElementsByTagName("Header0");
				parentNode = parentNodeList.item(1);
				childNodeList = parentNode.getChildNodes();						
				for(int x=0;x<childNodeList.getLength();x++)
				{				
					childNode = childNodeList.item(x);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equalsIgnoreCase("Detail1"))
					{
						errString = wfValData(dom,dom1,dom2,"1",editFlag,xtraParams);
						if(errString != null && errString.trim().length() > 0)
							break;
					}
					else if(childNodeName.equalsIgnoreCase("Detail2"))
					{						
						errString = wfValData(dom,dom1,dom2,"2",editFlag,xtraParams);
						if(errString != null && errString.trim().length() > 0)
							break;
					}	
					else if(childNodeName.equalsIgnoreCase("Detail3"))
					{
						errString = wfValData(dom,dom1,dom2,"3",editFlag,xtraParams);
						if(errString != null && errString.trim().length() > 0)
							break;
					}
				}
			}
			else
			{
				errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
			}
			*/
			// Modified by Rahul on 21/07/2015 [To avoid unwanted coding and confusion].End

		}
		catch(Exception e)
		{
			System.out.println("Exception : EmpBondAmount : wfValData(String xmlString) : ==>\n"+e.getMessage());
		}
		return (errString);
	}
	public String wfValData(Document dom, Document dom1, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		return "";
	}

	public String wfValData(String xmlString, String xmlString1,String xmlString2, String objContext, String editFlag) throws RemoteException,ITMException
	{
		return "";
	}
	public String itemChanged(Document dom, Document dom1,String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		return "";
	}
	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag) throws RemoteException,ITMException
	{
		return "";
	}
		
	public String wfValData(Document dom, Document dom1,Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0,cnt = 0;
		String childNodeName = null;
		String errString = "";
		String errCode = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		String userId = "";
		int currentFormNo=0,i=0;
		int childNodeListLength;
		//Modified by Rahul Shenoy on 22/07/2015 [Initialized Integers bondprdInt and bondamtDouble].Start
		int bondprdInt = 0;
		double bondamtDouble = 0;
		//Modified by Rahul Shenoy on 22/07/2015 [Initialized Integers bondprdInt and bondamtDouble].End		
		String empCode="",bondamt="",bondprd="",siteCode = "",lineno="";
				
		
		
		try
		{
			ConnDriver connDriver = new ConnDriver();
			GenericUtility genericUtility = GenericUtility.getInstance();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			
			
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			switch(currentFormNo)
			{
				case 1 :
					parentNodeList = dom.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"))
						{
							System.out.println("in emp_code item change -->>");
							empCode = getColumnValue("emp_code",dom);	
							
							if (empCode == null || empCode.trim().length() == 0 )
							{							
									errCode = "VNULEMPC";
									errString = getErrorString("emp_code",errCode,userId);
									break;	
							}
							else 
							{		
									String empSiteDB = "";
									String empSiteDOM = "";

									//sql = "select count(1) from employee where  emp_code = ? ";
									sql = "select emp_site , count(1) from employee where  emp_code = ? group by emp_site";
									pstmt=conn.prepareStatement(sql);
									pstmt.setString(1,empCode);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										empSiteDB = rs.getString(1);
										cnt = rs.getInt(2);
									}
									
									pstmt.close();
									rs.close();
									pstmt = null;
									rs = null;
									if(cnt == 0)
									{
										errCode = "VMEMPCD1";
										errString = getErrorString("emp_code",errCode,userId);
										
										break;
									}
									empSiteDOM = getColumnValue("emp_site",dom);
									empSiteDOM = empSiteDOM == null?"":empSiteDOM.trim();
									empSiteDB = empSiteDB == null?"":empSiteDB.trim();
									if (!empSiteDOM.equalsIgnoreCase(empSiteDB))
									{
										errCode = "VMEMPBND01";
										errString = getErrorString("emp_code",errCode,userId);
										
										break;
									}
									
									//Modified by RAHUL SHENOY on 04/08/2015 [Validation for Employment Status].Start
									String empStatus = "";
									sql ="select status from employee where emp_code = ?";
									pstmt = conn.prepareStatement(sql);
									pstmt.setString(1,empCode);
									rs = pstmt.executeQuery();
									
									if(rs.next())
									{
										empStatus = rs.getString("status");	
									}

									rs.close();
									pstmt.close();
									rs = null;
									pstmt = null;
									
									if(empStatus != null && empStatus.trim().equalsIgnoreCase("S"))
									{
										errCode = "VMEMPBND08";
										errString = getErrorString("emp_code",errCode,userId);
										break;
									}
									
									
									//Modified by RAHUL SHENOY on 04/08/2015 [Validation for Employment Status].End
									

								
							}
													
						}
						else if (childNodeName.equalsIgnoreCase("line_no"))
						{
							System.out.println("in line_no item change -->>");
							lineno = getColumnValue("line_no",dom);							


							if (lineno == null || lineno.trim().length() == 0 )
							{
									errCode = "VNULBLINE";
									errString = getErrorString("line_no",errCode,userId);
									break;
							}
							else
							{
								System.out.println("@ editFlag ---->>"+editFlag);
							  if (!( "E".equalsIgnoreCase(editFlag)))
							  {
								  System.out.println("@ editFlag  inside---->>"+editFlag);
									sql="select count(1) from employee_bond where emp_code = ? and line_no = ? ";
									pstmt=conn.prepareStatement(sql);
									pstmt.setString(1,empCode);
									pstmt.setString(2,lineno);
									rs = pstmt.executeQuery();
									if(rs.next())
									{
										cnt = rs.getInt(1);
									}
									pstmt.close();
									rs.close();
									pstmt = null;
									rs = null;
									if(cnt > 0)
									{
										errCode = "VETLINE";
										errString = getErrorString("line_no",errCode,userId);
										
										break;
									}
							   }
							}
							
						}
						
						
						else if (childNodeName.equalsIgnoreCase("bond_amt"))
						{
							System.out.println("in bond_amt item change -->>");
							bondamt = getColumnValue("bond_amt",dom);							


							if (bondamt == null || bondamt.trim().length() == 0 )
							{
									errCode = "VNULBAMT";
									errString = getErrorString("bond_amt",errCode,userId);
									break;
							}
							
							  
							//Modified by Rahul Shenoy on 22/07/2015 [Bond amount should be positive double value ].Start
						

							try
							{
								bondamtDouble = Double.parseDouble(bondamt);
							}
							
							 catch(Exception e)
							{
								errCode = "VMEMPBND06";	
								errString = getErrorString("bond_amt", errCode, userId);
								break;
							}
							
							if(bondamtDouble < 0)
							{
								errCode = "VMEMPBND04";
								errString = getErrorString("bond_amt", errCode, userId);
								break;
									
							}
							//Modified by Rahul Shenoy on 22/07/2015 [Bond amount should be positive double value ].End
							
							//Modified by RAHUL SHENOY on 04/08/2015 [Bond amount should not be 0 when adding].Start
							System.out.println("@ editFlag ---->>"+editFlag);
							  if (editFlag == null || !( "E".equalsIgnoreCase(editFlag)))
							  {
								  System.out.println("@ editFlag  inside---->>"+editFlag);
									
									if(bondamtDouble == 0)
									{
										errCode = "VMEMPBND07";
										errString = getErrorString("bond_amt",errCode,userId);
										break;
									}
							   }
							//Modified by RAHUL SHENOY on 04/08/2015 [Bond amount should not be 0 when adding].End
						}
						
						
						else if (childNodeName.equalsIgnoreCase("bond_prd"))
						{
							System.out.println("in ebond_prd item change -->>");
							bondprd = getColumnValue("bond_prd",dom);							


							if (bondprd == null || bondprd.trim().length() == 0 )
							{
									errCode = "VNULBPRD";
									errString = getErrorString("bond_prd",errCode,userId);
									break;
							}
							//Modified by Rahul Shenoy on 22/07/2015 [Bond period should be an Integer greater than 0].Start
							try
							{
								bondprdInt = Integer.parseInt(bondprd);
							}
							catch(Exception e)
							{
								errCode = "VMEMPBND05";
								errString = getErrorString("bond_prd", errCode, userId);
								break;
							}
							if(bondprdInt < 1)
							{
								errCode = "VMEMPBND03";
								errString = getErrorString("bond_prd", errCode, userId);
								break;
							}
							
							//Modified by Rahul Shenoy on 22/07/2015 [Bond period should be an Integer greater than 0].End
						
							
							//Modified by Rahul Shenoy on 20-07-2015 [Validation for duplicate bond period entries].Start
						
							sql = "";
							int cntBondPrd = 0;
							int lineNo = 0;
							String lineNoStr = "0";
							PreparedStatement bondPstmt;
							ResultSet bondRs;

							empCode = getColumnValue("emp_code",dom);							
							lineNoStr = getColumnValue("line_no",dom);							
							lineNoStr = lineNoStr == null || lineNoStr.trim().length() == 0?"0":lineNoStr.trim();
							try
							{
								lineNo = Integer.parseInt(lineNoStr);
							}
							catch (Exception e)
							{
								lineNo = 0;
							}
							
						 	sql = "select count(1) from employee_bond where emp_code = ? and bond_prd = ? and line_no <> ?";
							bondPstmt = conn.prepareStatement(sql);
							bondPstmt.setString(1, empCode);
							bondPstmt.setString(2, bondprd);
							bondPstmt.setInt(3, lineNo);
							bondRs = bondPstmt.executeQuery();
							
							if(bondRs.next())
							{
								cntBondPrd = bondRs.getInt(1);
							}
					
							if (bondRs != null)
							{
								bondRs.close();
								bondRs = null;
							}
							if (bondPstmt != null)
							{
								bondPstmt.close();
								bondPstmt = null;
							}

							if(cntBondPrd > 0)
							{
								errCode = "VMEMPBND02";
								errString = getErrorString("bond_prd", errCode, userId);
								break;
							}
							

							//Modified by Rahul Shenoy on 20-07-2015 [Validation for duplicate bond entries].End
				
							
						}
					}// for loop end
					break;
				
			} //end switch
			
		}//end try
		catch(Exception e)
		{			
			e.printStackTrace();
			errString = e.getMessage();
		}
		finally
		{
			try
			{
				if(conn!=null)
				{
					conn.close();
					conn = null;
				}				
				if(pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if(rs != null )
				{
					rs.close();
					rs = null;
				}
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}
		}		
		return errString;
	}
	
	public String itemChanged(String xmlString, String xmlString1,String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("IN ITEM CHANGE");
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String valueXmlString = "";
		
		try
		{
			dom = parseString(xmlString);			
			dom1 = parseString(xmlString1);
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [ChangeControlEJB][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
	{
		StringBuffer valueXmlString = new StringBuffer();
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		int ctr=0;
		String childNodeName = null;
		String columnValue = null;
		
		int currentFormNo = 0;
	
		String sql = "",empfname = "", empmname = "", emplname = "",empCode="";
		
		//MODIFIED by RAHUL SHENOY on 17/7/2015 [Initializing the new parameters].START
		String maxSql="";
		int emplLineNoMax =0;
		PreparedStatement maxPstmt = null;
		ResultSet maxRs = null;
		//MODIFIED by RAHUL SHENOY on 17/7/2015 [Initializing the new parameters].END
		ConnDriver connDriver = new ConnDriver();

		
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver=null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			// Modified by Piyush on 18/07/2015[To set login site in emp_site column on adding].Start
			String loginSite = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			loginSite = loginSite == null?"":loginSite;
			System.out.println("loginSiteCode ::-"+loginSite);
			// Modified by Piyush on 18/07/2015[To set login site in emp_site column on adding].End
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");

			switch(currentFormNo)
			{
			case 1 :
				valueXmlString.append("<Detail1>");
				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));

				// Modified by Piyush on 18/07/2015[To set login site in emp_site column on adding].Start
				if (currentColumn.trim().equals("itm_default"))
				{
					valueXmlString.append("<emp_site>").append("<![CDATA["+loginSite+"]]>").append("</emp_site>");
				}
				// Modified by Piyush on 18/07/2015[To set login site in emp_site column on adding].End
				else if(currentColumn.trim().equalsIgnoreCase("emp_code"))
				{
					
					empCode = genericUtility.getColumnValue("emp_code",dom);
					sql = " Select emp_fname,emp_mname,emp_lname from employee where emp_code= ?";   
							
					pstmt= conn.prepareStatement(sql);
					pstmt.setString(1,empCode);
					rs = pstmt.executeQuery();
				
					if(rs.next())
					{
						empfname = rs.getString(1) == null ? "" : rs.getString(1);
						empmname = rs.getString(2) == null ? "" : rs.getString(2);
						emplname = rs.getString(3) == null ? "" : rs.getString(3);	
					}
					
					pstmt.close();
					rs.close();
					pstmt = null;
					rs = null;
					
					//Modified by Rahul Shenoy on 17/7/2015 [for querying maximum value from table employee_bond ].START 
					// Modified by Rahul on 21/07/2015 [Table name was wrongly specified]
					// maxSql ="select max(line_no) from employeed_bond where emp_code= ?";
					maxSql ="select max(line_no) from employee_bond where emp_code= ?";
					maxPstmt = conn.prepareStatement(maxSql);
					maxPstmt.setString(1,empCode);
					maxRs = maxPstmt.executeQuery();
					
					if(maxRs.next())
					{
						emplLineNoMax = maxRs.getInt(1);				
					}
					emplLineNoMax = emplLineNoMax + 1;
					//Modified by Rahul Shenoy on 17/7/2015 [for appending maximum value from table employee_bond ].END
					
					valueXmlString.append("<emp_fname>").append("<![CDATA["+empfname+"]]>").append("</emp_fname>");
					valueXmlString.append("<emp_mname>").append("<![CDATA["+empmname+"]]>").append("</emp_mname>");
					valueXmlString.append("<emp_lname>").append("<![CDATA["+emplname+"]]>").append("</emp_lname>");
					valueXmlString.append("<line_no protect=\"1\">").append("<![CDATA["+emplLineNoMax+"]]>").append("</line_no>");  //Modified by RAHUL SHENOY on 17/7/2015 [for appending maximum value from table employee_bond ]
					
					System.out.println("First Name :"+empfname+" Middle Name :"+empmname+" Last Name :"+emplname);
					
					if(maxRs != null)
					{
						maxRs.close();
						maxRs = null;
					}
					if(maxPstmt!= null)
					{
						maxPstmt.close();
						maxPstmt = null;
					}
					//Modified by Rahul Shenoy on 17/7/2015 [Introducing Counter in Line_No column].End
					
				}	
				valueXmlString.append("</Detail1>");
				break;
			}// end switch
			valueXmlString.append("</Root>");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();			
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn!=null)
				{	
					conn.close();
					conn = null;
				}
				if(pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if(rs != null)
				{
					rs.close();
					rs = null;
				}
				//Modified by Rahul Shenoy on 17/7/2015 [Closing connections for created resources].START
				if(maxRs != null)
				{
					maxRs.close();
					maxRs = null;
				}
				if(maxPstmt!= null)
				{
					maxPstmt.close();
					maxPstmt = null;
				}
				
				//Modified by Rahul Shenoy on 17/7/2015 [Closing connections for created resources].END
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
		}
		System.out.println("Return xml ---->>>>"+valueXmlString.toString());
		return valueXmlString.toString();
	}

}
