package ibase.webitm.ejb.fin.adv;

import java.rmi.RemoteException;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import java.io.*;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.system.config.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class MiscVoucherAct extends ActionHandlerEJB implements MiscVoucherActLocal,MiscVoucherActRemote // SessionBean
{
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate() 
	{
	}

	public void ejbPassivate() 
	{
	}*/

	public String actionHandler() throws RemoteException,ITMException
	{
		return "";
	}
	
	public String actionHandler(String actionType, String xmlString, String objContext, String xtraParams) throws RemoteException,ITMException
	{
		Document dom = null;
		String  resString = null;
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				System.out.println("xmlString :: "+xmlString);
				dom = GenericUtility.getInstance().parseString(xmlString); 
			}
			if (actionType.equalsIgnoreCase("Default"))
			{
				resString = actionDefault(dom,objContext,xtraParams);
			}
		}
	   	catch(Exception e)
		{
			System.out.println("Exception :MiscVoucher :actionHandler(String xmlString):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning from actionVoucher actionHandler"+resString);
	    return resString;
	}
	
	private String actionDefault(Document dom, String objContext, String xtraParams) throws RemoteException , ITMException
	{
		String sundryType = "", sql = "", detCnt = "0", empCode  = "", sundryCode  = "", cctrCode = "", acctCode ="", grade = "", billNo = "", billDate = "";
		StringBuffer valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root>");
		StringBuffer xmlString = new StringBuffer("<?xml version=\"1.0\"?><Root>");
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String xmlData = "",nodeValue = "";
		ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		try
		{
			detCnt = GenericUtility.getInstance().getValueFromXTRA_PARAMS(xtraParams,"detCnt"); 
			if (detCnt.equals("0"))
			{
				conn = connDriver.getConnectDB("DriverITM");
				stmt = conn.createStatement();

				sundryType = GenericUtility.getInstance().getColumnValue("sundry_type",dom);
				System.out.println("sundryType : "+sundryType);
				if (sundryType.equalsIgnoreCase("E")) 
				{
					empCode = GenericUtility.getInstance().getColumnValue("sundry_code",dom);
					System.out.println("empCode  :"+empCode);
					sql = "SELECT CCTR_CODE__SAL, GRADE FROM EMPLOYEE WHERE EMP_CODE = '"+empCode+"'";
					rs = stmt.executeQuery(sql);					
					if (rs.next())
					{
						cctrCode = rs.getString("CCTR_CODE__SAL");
						grade = rs.getString("GRADE");
					}
					System.out.println("cctrCode  :"+cctrCode+" grade :"+grade);
					if (cctrCode == null || cctrCode.trim().length() == 0)
					{
						sql = "SELECT ACCT_CODE__EXP, CCTR_CODE__EXP FROM GRADE WHERE GRADE_CODE = '"+grade+"'";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							acctCode = rs.getString("ACCT_CODE__EXP");
							cctrCode = rs.getString("CCTR_CODE__EXP");
						}
						System.out.println("acctCode  :"+acctCode+" cctrCode :"+cctrCode);
					}
					else
					{
						sql = "SELECT ACCT_CODE__EXP FROM GRADE WHERE GRADE_CODE = '"+grade+"'";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							acctCode = rs.getString("ACCT_CODE__EXP");
						}
						System.out.println("acctCode  :"+acctCode);
					}
				}
				else if (sundryType.equalsIgnoreCase("P"))
				{
					sundryCode = GenericUtility.getInstance().getColumnValue("sundry_code",dom);
					System.out.println("sundryCode  :"+sundryCode);
					sql = "SELECT EMP_CODE FROM SALES_PERS WHERE SALES_PERS = '"+sundryCode+"'";
					rs = stmt.executeQuery(sql);
					if (rs.next())
					{
						empCode = rs.getString("EMP_CODE");
					}
					if (empCode != null && empCode.trim().length() > 0)
					{
						sql = "SELECT CCTR_CODE__SAL, GRADE FROM EMPLOYEE WHERE EMP_CODE = '"+empCode+"'";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							cctrCode = rs.getString("CCTR_CODE__SAL");
							grade = rs.getString("GRADE");
						}
						if (cctrCode == null || cctrCode.trim().length() == 0)
						{
							sql = "SELECT ACCT_CODE__EXP, CCTR_CODE__EXP FROM GRADE WHERE GRADE_CODE = '"+grade+"'";
							rs = stmt.executeQuery(sql);
							if (rs.next())
							{
								acctCode = rs.getString("ACCT_CODE__EXP");
								cctrCode = rs.getString("CCTR_CODE__EXP");
							}
						}
						else
						{
							sql = "SELECT ACCT_CODE__EXP FROM GRADE WHERE GRADE_CODE = '"+grade+"'";
							rs = stmt.executeQuery(sql);
							if (rs.next())
							{
								acctCode = rs.getString("ACCT_CODE__EXP");
							}
						}//end else
					}//end if
				}//end else
				System.out.println("acctCode :"+acctCode+" cctrCode :"+cctrCode+" grade :"+grade+" billNo :"+billNo+" billDate :"+billDate);
				billNo = GenericUtility.getInstance().getColumnValue("bill_no",dom);
				billDate = GenericUtility.getInstance().getColumnValue("bill_date",dom);
				System.out.println("billNo  :"+billNo+" billDate :"+billDate);
				String xmlFile = ".." + File.separator + "resource" + File.separator + "ITM" + File.separator+"MvouchClaim.xml";
				System.out.println("xmlFilePath :"+xmlFile);
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(xmlFile);
				xmlData = GenericUtility.getInstance().serializeDom(doc);
				System.out.println("xmlDate  Before Update :\n"+xmlData);

				xmlString.append("<Detail>");
				if (cctrCode != null && cctrCode.trim().length() > 0)
				{
					xmlString.append("<cctr_code>").append(cctrCode).append("</cctr_code>");
				}
				if (acctCode != null && acctCode.trim().length() > 0)
				{
					xmlString.append("<acct_code>").append(acctCode).append("</acct_code>");
				}
				if (billNo != null && billNo.trim().length() > 0)
				{
					xmlString.append("<bill_no>").append(billNo).append("</bill_no>");
				}
				if (billDate != null && billDate.trim().length() > 0)
				{
					xmlString.append("<bill_date>").append(billDate).append("</bill_date>");
				}
				xmlString.append("<bill_amt>").append("0").append("</bill_amt>");
				xmlString.append("</Detail>");
				xmlString.append("</Root>");
				System.out.println("xmlString :"+xmlString);

				Document docSmall = GenericUtility.getInstance().parseString(xmlString.toString());			

				NodeList metaDataList = doc.getElementsByTagName("Detail");
				NodeList importedList = docSmall.getElementsByTagName("Detail");

				int metaDataNodeListLen = metaDataList.getLength();
				int importedListLen = importedList.getLength();
				System.out.println("\n metaDataNodeListLen :"+metaDataNodeListLen+"\n importedListLen :"+importedListLen);
				
				//Added by jiten
				boolean flag = false;
				NodeList childNodeList = null;
				childNodeList = importedList.item(0).getChildNodes();
				int importedListLength = childNodeList.getLength();
				for (int ctr = 0;ctr < importedListLength;ctr++)
				{
					Node currNode = childNodeList.item(ctr);
					String childNodeName = currNode.getNodeName();
					System.out.println("Current Node Name :: "+childNodeName);
					for (int i = 0;i < metaDataNodeListLen;i++ )
					{
						flag = false;
						Node currDetailNode = metaDataList.item(i);
						NodeList currDetailChildList = currDetailNode.getChildNodes();
						int currDetailChildListlen = currDetailChildList.getLength();
						for (int j =0;j < currDetailChildListlen;j++ )
						{
							String currDetailChildNodeName = currDetailChildList.item(j).getNodeName();
							if (childNodeName.equalsIgnoreCase(currDetailChildNodeName))
							{
								Node updatedNode = doc.importNode(currNode, true);
								currDetailNode.replaceChild(updatedNode,currDetailChildList.item(j));
								flag = true;
								break;
							}
						}
						if (flag == false)
						{
							Node updatedNode = doc.importNode(currNode, true);
							currDetailNode.appendChild(updatedNode);
						}						
					}
				}//End				
				xmlData = GenericUtility.getInstance().serializeDom(doc);
				System.out.println("xmlData  After Updation :\n"+xmlData);
				Document finalDom = GenericUtility.getInstance().parseString(xmlData); 
				NodeList finalNodeList = finalDom.getElementsByTagName("Detail");
				int finalNodeListLen = finalNodeList.getLength();
				for (int prnt = 0 ;prnt < finalNodeListLen; prnt++)
				{
					valueXmlString.append("<Detail>\r\n");
					Node finalNode = finalNodeList.item(prnt);
					NodeList finalChildNodeList = finalNode.getChildNodes();
					int fianlchildNodeListLen = finalChildNodeList.getLength();					
					for (int chld = 0; chld < fianlchildNodeListLen ; chld++)
					{
						Node fianalChildNode = finalChildNodeList.item(chld);
						String childNodeName = fianalChildNode.getNodeName();
						if (fianalChildNode.getNodeType() == Node.ELEMENT_NODE)
						{
							if (fianalChildNode.hasChildNodes())
							{
								nodeValue = fianalChildNode.getFirstChild().getNodeValue(); 						
							}
							valueXmlString.append("<").append(childNodeName).append(" isSrvCallOnChg='0'>").append("<![CDATA[").append(nodeValue == null?"":nodeValue).append("]]>").append("</").append(childNodeName).append(">\r\n");
							nodeValue = "";
						}
					}
					valueXmlString.append("</Detail>\r\n");
				}				
			}//end if detCnt
			valueXmlString.append("</Root>");			
			System.out.println("valueXmlString from for:\n"+valueXmlString.toString());
		}// end try
		catch(SQLException e)
		{
			System.out.println("Exception : MiscVoucher : actionDefault " +e.getMessage());
			throw new ITMException(e);
		}
		catch(Exception e)
		{
			System.out.println("Exception : MiscVoucher : actionHandler :(Document dom)" +e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection........");
				if (conn != null)
				{
					conn.close();
					conn = null;
				}				
			}catch(SQLException se){}
		}
		System.out.println("valueXmlString :"+valueXmlString);
		return valueXmlString.toString();
	}
}