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.io.StringWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.w3c.dom.Document;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; 
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;



@Stateless 
public class EmpBondDefinitionPrs extends ValidatorEJB implements EmpBondDefinitionPrsLocal,EmpBondDefinitionPrsRemote 
{
	
	public String preSave() throws RemoteException,ITMException
	{
		return "";
	}


	public String preSave(String xmlString, String editFlag, String xtraParams, Connection conn) throws RemoteException,ITMException
	{
		String errString = null;
		Document dom = null;
		boolean isError = false;
		//Added by RAHUL SHENOY
		Document updateDom = null;
		NodeList parentNodeList = null;
		//Added by RAHUL SHENOY
		
		System.out.println("\n\n xmlString in preSave \n:" + xmlString + "\n");
	
		try
		{
			dom = parseString(xmlString);
			//Added by RAHUL SHENOY on 02/09/2015 [Filtering deleted entries from dom].Start
			parentNodeList = dom.getElementsByTagName("Detail2"); 
			
			if(parentNodeList.getLength() > 0)
			{
				System.out.println("*** Inside formatting string ***");
				
				StringBuffer tempXmlString = new StringBuffer() ;
				tempXmlString.append(xmlString);
				
				StringBuffer  valueXmlString = new StringBuffer();
				valueXmlString = getBifurDomValue(dom, "2");
				
				tempXmlString.replace(tempXmlString.indexOf("<Detail2"), tempXmlString.lastIndexOf("</Detail2>")+"</Detail2>".length(), valueXmlString.toString());
				System.out.println("New updated document 2 object is --->"+tempXmlString);
				
				if(tempXmlString != null && tempXmlString.toString().trim().length() > 0)
				{
					updateDom = parseString(tempXmlString.toString());
				}
			
				errString = preSaveLogic(updateDom, editFlag, xtraParams, conn);
			}else
			{
				errString = preSaveLogic(dom, editFlag, xtraParams, conn);
			}
			//Added by RAHUL SHENOY on 02/08/2015 [Filtering deleted entries from dom].End 
			//dom = parseString(xmlString);
			//errString = preSaveLogic(dom, editFlag, xtraParams, conn);
		}
		catch(Exception e)
		{
			System.out.println("Exception :EmpCompletePrs : :==>\n"+e.getMessage());
			e.printStackTrace();
			isError = true;
			throw new ITMException(e);
		}
		return (errString);
	}

//	private String preSaveLogic(Document dom, String editFlag, String xtraParams, Connection conn) throws RemoteException,ITMException
//	{
//		String errString = "";
//		try
//		{
//			errString = checkDuplicateRecordsfromDom(dom, editFlag, xtraParams, conn);
//		}
//		catch(Exception e)
//		{			
//			System.out.println("Exception :EmpCompletePrs : :==>\n"+e.getMessage());
//			e.printStackTrace();
//			throw new ITMException(e);
//		}
//		finally
//		{
//			
//		
//			
//		}		
//		return errString;
//
//	}

	public String preSaveLogic(Document dom,String editFlag, String xtraParams, Connection conn) 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 = "";
		String empStatus = "",lineNoRef="";
		int bondprdInt = 0, lineNoRefInt = 0;
		int lineNoMaster = 0;
		boolean sameBondPeriod = false;
		int cntBondPrd = 0;

		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		String userId = "";
		int currentFormNo=0,i=0;
		int childNodeListLength;		
		
		String empCode="",bondamt="",bondprd="",siteCode = "";
		SimpleDateFormat simpleDateFormat = null;		
		
		
		try
		{
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			GenericUtility genericUtility = GenericUtility.getInstance();
			simpleDateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			
			
					parentNodeList = dom.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();
						//Modified by RAHUL SHENOY on 11/08/2015 [Reference Line Number validation].Start
						if (childNodeName.equalsIgnoreCase("line_no__ref"))
						{
						lineNoRef = childNode.getFirstChild().getNodeValue().trim();
						}
						
						if (childNodeName.equalsIgnoreCase("bond_prd"))
						{
							bondprd = childNode.getFirstChild().getNodeValue().trim();
						
							bondprd = (bondprd == null ) ? "0" : bondprd.trim() ;
									
							//Modified by Rahul Shenoy on 02/09/2015 [Revised Bond period Validations].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;
							}
									
							if(checkDuplicateBondPeriod(dom))
							{
								System.out.println("*** Duplicate records available in Current Transaction ***");
								errCode = "VMEMPBND09";
								errString = getErrorString("bond_prd", errCode, userId);
								break;
							}
										
							empCode = genericUtility.getColumnValue("emp_code",dom);	
							
							System.out.println("lineNoRef..["+lineNoRef+"]");
							
							lineNoRef = lineNoRef == null || lineNoRef.trim().length() == 0 ? "0":lineNoRef.trim();
										
							try
							{
								lineNoRefInt = Integer.parseInt(lineNoRef);
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
							//Duplicate Bond period validation in employee bond master
							
						 	sql = "select count(1) from employee_bond where emp_code = ? and bond_prd = ? and line_no <> ?";
							pstmt= conn.prepareStatement(sql);
							pstmt.setString(1, empCode);
							pstmt.setInt(2, bondprdInt);
							pstmt.setInt(3, lineNoRefInt);
							rs = pstmt.executeQuery();
							
							if(rs.next())
							{
								cntBondPrd = rs.getInt(1);
							}
					
							closeResources(pstmt,rs);
							
							if(cntBondPrd == 1)
							{
								sql = "select line_no from employee_bond where emp_code =? and bond_prd = ?";
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, empCode);
								pstmt.setInt(2, bondprdInt);
								rs = pstmt.executeQuery();
								
								while(rs.next())
								{
									lineNoMaster = rs.getInt("line_no");
								}
								
								closeResources(pstmt, rs);
								
								sameBondPeriod = duplicateBondPeriodValidation(dom,lineNoMaster,bondprdInt);
								
								if(sameBondPeriod == false)
								{//Duplicate Bond period in master
									System.out.println("*** DUPLICATE BOND PERIOD ***");
									errCode = "VMEMPBND02";
									errString = getErrorString("bond_prd", errCode, userId);
									break;
								}
							}			
							//Modified by Rahul Shenoy on 11/08/2015 [Revised Bond period Validations].End
						}
				}// for loop end
		} //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;
	}
	
	//Added by RAHUL SHENOY on 21/08/2015 [Validation for duplicate value in the same transaction].Start
	private boolean checkDuplicateBondPeriod(Document dom)
	 
	{
		
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		
		String bondPrd= "";
		int bondPrdInt =0;
		int prntCtrRec = 0;
		
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		
		
		boolean isDuplRecord = false;
		
		try {
			System.out.println("********---- Entering the Method : checkDuplicateBondPeriod ---- ********");
			parentList = dom.getElementsByTagName("Detail2");
			int parentNodeListLength = parentList.getLength();
			
			System.out.println(" checkDuplicateBondPeriod parentList.getLength() ["+parentList.getLength()+"]");
			
			for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
			{	
				parentNode = parentList.item(prntCtr);
				System.out.println(" ParentNode["+parentNode+"]");	
				prntCtrRec++;
				childList = parentNode.getChildNodes();
				System.out.println(" ChildList.getLength() ["+childList.getLength()+"]");		
				for (int ctr = 0; ctr < childList.getLength(); ctr++)
				{
					childNode = childList.item(ctr);
					System.out.println("childNode.getNodeName() ....["+childNode.getNodeName()+"]");
				
					if ( childNode != null && childNode.getFirstChild() != null &&  
					childNode.getNodeName().equalsIgnoreCase("bond_prd") )
					{
						bondPrd= childNode.getFirstChild().getNodeValue().trim();

						System.out.println("Value in Dom......["+bondPrd+"]");
						
						try 
						{
							bondPrdInt = Integer.parseInt(bondPrd);
						}
						catch(Exception e)
						{
							System.out.println("Parsing Failed inside Method ::::::>>>>>> checkDuplicateRecordsfromDom");
						}
							 
						System.out.println("Values in ArrayList..... ["+ arrayList +"]");
						
						if(arrayList.contains(bondPrdInt))
						{
							return true;					
						}
						else 
						{
							System.out.println("***Value added to ArrayList*** \n"+ "Value is  :" + " ["+bondPrd+"] ");
							
							arrayList.add(bondPrdInt);
						
						}
					}
				}//End Inner For loop
			}//End Outer For loop
			System.out.println(" Bond periods avaliable on the dom are : ["+arrayList+"]");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return isDuplRecord;
	}
	//Added by RAHUL SHENOY on 21/08/2015 [Validation for duplicate value in the same transaction].End

 
	private void closeResources(PreparedStatement pstmt,ResultSet rs)
	{
		
	try{
			if (rs != null)
			{
				rs.close();
				rs = null;
			}
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
  	
	//Added by RAHUL SHENOY on 02/09/2015 [for skipping the deleted record from dom ].Start
	public  StringBuffer getBifurDomValue(Document dom, String currentForm) throws ITMException
    {
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		ArrayList<String> delDomId = new ArrayList<String>();
		String domId = "";
		
		String columnValue = "";
		StringBuffer tempXmlString = new StringBuffer();
		
		try
		{
			parentList = dom.getElementsByTagName("Detail"+currentForm);
			int parentNodeListLength = parentList.getLength();
			System.out.println("document"+parentNodeListLength);
			
			for(int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
			{
				  parentNode = parentList.item(prntCtr);
				  
				  if(parentNode != null &&  parentNode.getNodeName().equalsIgnoreCase("Detail2"))
					{
					   domId = parentNode.getAttributes().getNamedItem("domID").getNodeValue();
					}
					childList = parentNode.getChildNodes();
					for (int ctr = 0; ctr < childList.getLength(); ctr++)
					{
						childNode = childList.item(ctr);
						
						if(childNode != null &&  childNode.getNodeName().equalsIgnoreCase("attribute"))
						{
							String updateFlag = "";
							updateFlag =   childNode.getAttributes().getNamedItem("updateFlag").getNodeValue();
							
							System.out.println("[getPlaceOfWorkValueFromDom][updateFlag]" +updateFlag);
							if (updateFlag.equalsIgnoreCase("D"))
							{	
								delDomId.add(domId.trim());
							}
						}					
	
					}
			}	
			System.out.println("Deleted dom id list -->"+delDomId);
			
			for(int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
			{
				domId ="";
				parentNode = parentList.item(prntCtr);

				System.out.println("prntCtr["+prntCtr+"]");				
				System.out.println("parentNode.getNodeValue()["+parentNode.getNodeValue()+"]");				
				System.out.println("parentNode.getTextContent()["+parentNode.getTextContent()+"]");	
				System.out.println("parentNode["+nodeToString(parentNode)+"]");	
				
					if(parentNode != null &&  parentNode.getNodeName().equalsIgnoreCase("Detail2"))
					{
					   domId = parentNode.getAttributes().getNamedItem("domID").getNodeValue();
					}
					if (!delDomId.contains(domId))
					{	
						tempXmlString.append(nodeToString(parentNode)) ;
					}
					
					
			}
			System.out.println("tempXmlString----------> ["+tempXmlString+"]");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}		
		return tempXmlString;
	}


	public static String nodeToString(Node node) 
	{
		StringWriter sw = new StringWriter();
		try 
		{
			 Transformer t = TransformerFactory.newInstance().newTransformer();
			 t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			 t.setOutputProperty(OutputKeys.INDENT, "yes");
			 t.transform(new DOMSource(node), new StreamResult(sw));
		} 
		catch (TransformerException te) 
		{
		 System.out.println("nodeToString Transformer Exception");
		}
		return sw.toString();
	}
	//Added by RAHUL SHENOY on 02/09/2015 [for skipping the deleted record from dom ].End

	//Added by RAHUL SHENOY on 02/09/2015 [Checking duplicate bond period entry].Start
	private boolean duplicateBondPeriodValidation(Document dom,int lineNo,int bondprdInt)
  	{

	 		NodeList parentList = null;
	 		NodeList childList = null;
	 		Node parentNode = null;
	 		Node childNode = null;
	 		
	 		ArrayList<Integer> lineNoList = new ArrayList<Integer>();
	 		
	 		int lineNoExistingInt = 0,bondPrdInDomInt = 0;
	 		
	 		String lineNoExisting = "",bondPrdInDom ="";
	 		
	 		boolean exists = false;
	 		
	 		try {
		 			System.out.println("********---- Entering the Method : checkChangedBondPeriod  ---- ********");
		 			parentList = dom.getElementsByTagName("Detail2");
		 			int parentNodeListLength = parentList.getLength();
		 			
		 			System.out.println(" getValidDateFromDom parentList.getLength() ["+parentList.getLength()+"]");
		 			int prntCtrRec = 0;
		 			for (int prntCtr = 0; prntCtr < parentNodeListLength; prntCtr++ )
		 			{	
		 				parentNode = parentList.item(prntCtr);
		 				System.out.println(" getValidDateFromDom parentNode["+parentNode+"]");	
		 				prntCtrRec++;
		 				childList = parentNode.getChildNodes();
		 				System.out.println(" getValidDateFromDom childList.getLength() ["+childList.getLength()+"]");		
		 				for (int ctr = 0; ctr < childList.getLength(); ctr++)
		 				{
		 					childNode = childList.item(ctr);
		 					System.out.println("childNode.getNodeName() ....["+childNode.getNodeName()+"]");
		 				
		 					if ( childNode != null && childNode.getFirstChild() != null &&  
		 					childNode.getNodeName().equalsIgnoreCase("line_no__ref") )
		 					{
		 						lineNoExisting= childNode.getFirstChild().getNodeValue().trim();
		 						try{
		 							lineNoExistingInt = Integer.parseInt(lineNoExisting);
		 						}catch(Exception e)
		 						{
		 							lineNoExistingInt = 0;
		 						}
		 						
		 						System.out.println("*** Line Number Reference saved in the lineNoList ::>> ["+lineNoExisting+"] ***");
		 						lineNoList.add(lineNoExistingInt);
		 						
		 						if(lineNoExistingInt == lineNo)
		 						{
		 							if ( childNode != null && childNode.getFirstChild() != null &&  
		 				 					childNode.getNodeName().equalsIgnoreCase("bond_prd") )
		 							{
		 								bondPrdInDom =childNode.getFirstChild().getNodeValue().trim();
		 								
		 								try{
		 									bondPrdInDomInt =Integer.parseInt(bondPrdInDom);
		 								}catch(Exception e)
		 								{
		 									e.printStackTrace();
		 								}
		 							}
		 						}
		 					}	
		 				}//end inner for loop
		 			}//end outer for loop
		 			
		 			
		 			System.out.println("*** Line Number List : "+ lineNoList + " ***");
		 			if(lineNoList.contains(lineNo) )
		 			{
		 				if(bondPrdInDomInt == bondprdInt )
		 				{
		 					System.out.println("Line Number and Bond Period combination exists in the dom ");
		 					System.out.println("Value of Line Number : ["+ lineNo +"]");
		 					System.out.println("Value of Bond Period : ["+bondPrdInDomInt +"");
			 				exists = false;	
		 				}else{
		 				
		 					exists = true;
	 						}
		 			}else
		 			{
		 				System.out.println("***Line Number DOESNT exist in the dom***");
		 				exists = false;
		 			}
		 			
	 			}//end try
	 			catch(Exception e)
	 			{
	 				e.printStackTrace();
	 			}
	 		
	 		return exists;
  		
  		}
  		//Added by RAHUL SHENOY on 02/09/2015 [Checking duplicate bond period entry].End  
  		
  	
}//end class
