package ibase.webitm.ejb.adm.adv;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;


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;

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

import ibase.system.config.ConnDriver;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.ejb.ActionHandlerEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.ITMException;

@Stateless
public class EmpBondDefault extends ActionHandlerEJB implements  EmpBondDefaultLocal,EmpBondDefaultRemote
{
	public String actionHandler(String actionType, String xmlString, String objContext, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retString = "";
				
		try
		{
			dom = genericUtility.parseString(xmlString);
			 
			retString = actionHandler(actionType, dom, objContext, xtraParams);
				
		}
		catch (Exception ex)
		{
			System.out.println("in catch");
			ex.printStackTrace();
			throw new ITMException(ex);
		}
		
		return retString;
	}

	private String actionHandler(String actionType, Document dom, String objContext, String xtraParams) throws ITMException
	{
		String sql = "", childNodeName = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
		NodeList parentNodeList = null, childNodeList = null;
		Node parentNode = null, childNode = null;
		
		//Added by RAHUL SHENOY on 19/08/2015 
		NodeList parentNodeListDet2 = null;
		
		int bondAmt=0,bondPrd=0;
		GenericUtility genericUtility;
		StringBuffer valueXmlBuff;
		String retString = "",empcode="", userId = "";
		ValidatorEJB validatorEJB;

		int lineNo=0;
		int totalRowCnt = 0;
		int deletedRowCnt = 0;
		try
		{
			validatorEJB = new ValidatorEJB();
			userId = validatorEJB.getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			valueXmlBuff = new StringBuffer();
			genericUtility = GenericUtility.getInstance();
		  
			  
			valueXmlBuff.append("<?xml version=\"1.0\"?>\r\n");
			valueXmlBuff.append("<Root>\r\n");

			parentNodeList = dom.getElementsByTagName("Detail1");
				
			//loginEmpCode = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams, "loginEmpCode");
				
			   
			for (int i = 0; i < parentNodeList.getLength(); i++)
			{
				parentNode = parentNodeList.item(i);
				childNodeList = parentNode.getChildNodes();

				for (int j = 0; j < childNodeList.getLength(); j++)
				{
					childNode = childNodeList.item(j);
					childNodeName = childNode.getNodeName();							
				}
			}
			    
			
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			
			//Modified by RAHUL SHENOY on 19/08/2015 [Fetch and display data only if no rows are present in detail2].Start
				
			parentNodeListDet2 = dom.getElementsByTagName("Detail2");
			totalRowCnt = parentNodeListDet2.getLength();
			if (totalRowCnt > 0)
			{
				deletedRowCnt = getDeletedRowCnt(dom, "2");
				totalRowCnt = totalRowCnt - deletedRowCnt;
			}
			if(totalRowCnt == 0)
			{
				System.out.println("*** ParentNodeListDet2 Length==>>" + parentNodeListDet2.getLength() +" ***");
				
				empcode = genericUtility.getColumnValue("emp_code",dom);
				
				sql="select line_no,bond_prd,bond_amt from employee_bond  where emp_code= ?  ";
				
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, empcode);
				rs = pstmt.executeQuery();
				
				while (rs.next())
				{
				   // lineNo++;	
					lineNo=rs.getInt("LINE_NO");
					bondAmt = rs.getInt("BOND_AMT");
					bondPrd = rs.getInt("BOND_PRD");
						
				
					valueXmlBuff.append("<Detail>\r\n");		
					//Modified by RAHUL SHENOY on 12/08/2015 [Line number increment provided by Framework]
					//valueXmlBuff.append("<line_no>").append("<![CDATA["+lineNo+"]]>").append("</line_no>");
					
					//Modified by RAHUL SHENOY on 11/08/2015 [Display Line Number in the newly added line_no__ref field].Start
					valueXmlBuff.append("<line_no__ref>").append("<![CDATA["+lineNo+"]]>").append("</line_no__ref>");
					//Modified by RAHUL SHENOY on 11/08/2015 [Display Line Number in the newly added line_no__ref field].End
				
					valueXmlBuff.append("<bond_amt__curr>").append("<![CDATA["+bondAmt+"]]>").append("</bond_amt__curr>");
					valueXmlBuff.append("<bond_prd__curr>").append("<![CDATA["+bondPrd+"]]>").append("</bond_prd__curr>");
					
					valueXmlBuff.append("<bond_amt>").append("<![CDATA["+bondAmt+"]]>").append("</bond_amt>");
					valueXmlBuff.append("<bond_prd>").append("<![CDATA["+bondPrd+"]]>").append("</bond_prd>");
					
					valueXmlBuff.append("</Detail>\r\n");
					
					System.out.println("------->>>>Line no :"+lineNo+" Bond Amt :"+bondAmt+" bond period : "+bondPrd);			
			
				}
					
			}
			valueXmlBuff.append("</Root>\r\n");
				
			//Modified by RAHUL SHENOY on 19/08/2015 [Fetch and display data only if no rows are present in detail2].End
					
			if (pstmt != null)
			{
				pstmt.close();
				pstmt = null;
			}
			
			if (rs != null)
			{
				rs.close();
				pstmt = null;
			}
			
			System.out.println("ValueXmlBuff found to be ::::::::::::::::::::\n"+valueXmlBuff.toString()+"\n\n");
			retString = valueXmlBuff.toString();		
			
			System.out.println("Return String ..in deafault EJB ----------->>>>>>>>>>> \n" + retString);

			return retString;
			
		}
		catch (Exception e)
		{
			System.out.println("Exception : TrainingDefault : actionHandler " + e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		//return retString;
	}
	 
	//Added by RAHUL SHENOY on 20/08/2015 [Getting the deleted Row count].Start
	private int getDeletedRowCnt(Document dom,String currentForm)
	{
		NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		
		int delRowCount = 0;
		
		System.out.println("**** Inside the Method :::: getDeletedRowCount ****");
		
		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);

				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"))
						{	
							delRowCount = delRowCount + 1;
							System.out.println("*** delRowCount ===>>> ["+delRowCount+"]");
						}
					}					

				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println("Final value of delRowCount being returned is  ::::>>>> " + delRowCount);
		return delRowCount;
	}
	//Added by RAHUL SHENOY on 20/08/2015 [Getting the deleted Row count].End
			
}