/*
Window Name : w_misc_voucher 
Button name : Process
Action		: Update  MISC_VOUCHER_TRACE Table.
*/
package ibase.webitm.ejb.fin.adv;

import java.sql.*;
import org.w3c.dom.*;
import javax.ejb.*;
import java.rmi.RemoteException;

import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.TransIDGenerator;
import ibase.webitm.utility.ITMException;
import ibase.system.config.*;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class MiscVouchTdsPrc extends ProcessEJB implements MiscVouchTdsPrcLocal,MiscVouchTdsPrcRemote //SessionBean 
{
	/*public void ejbCreate() throws RemoteException,CreateException
	{
	}

	public void ejbRemove()
	{
	}

	public void ejbActivate()
	{
	}

	public void ejbPassivate()
	{
	}*/

	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("In getData() Method of MiscVouchTdsEJB ::");
		Document dom1 = null,dom2 = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retString = "";
		try
		{
			dom1 = genericUtility.parseString(xmlString);
			dom2 = genericUtility.parseString(xmlString2);
			retString = getData(dom1,dom2,windowName,xtraParams);			
		}
		catch(Exception se)
		{
			System.out.println("Exception in MiscVouchTdsEJB :: "+se.getMessage());
			throw new ITMException(se);
		}
		return retString;
	}
	public String getData(Document dom, Document dom2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		String tranId = "";
		String vouchType = "",errCode = "",errString = "";
		int cnt = 0;
		StringBuffer retString = new StringBuffer();
		ConnDriver connDriver = new ConnDriver();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			stmt = conn.createStatement();
			tranId = genericUtility.getColumnValue("tran_id",dom);
			sql = "SELECT VOUCH_TYPE FROM MISC_VOUCHER WHERE TRAN_ID = '"+tranId+"'";
			System.out.println("Exceutin SQL :: "+sql);
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				vouchType = rs.getString("VOUCH_TYPE");				
			}
			if (!vouchType.equalsIgnoreCase("T"))
			{
				errCode = "VTVOUCH3";
			}
			System.out.println("Voucher Type :: "+vouchType);
			sql = "SELECT COUNT(*) AS COUNT FROM MISC_VOUCHER_TRACE WHERE TRAN_ID = '"+tranId+"' AND TRAN_ID__SER IS NULL";
			rs = stmt.executeQuery(sql);
			if (rs.next())
			{
				cnt = rs.getInt("COUNT");
			}
			if (cnt == 0)
			{
				errCode = "VTNOREC";
			}
			if (errCode.equals(""))
			{
				sql = "SELECT MISC_VOUCHER_TRACE.TRAN_ID, MISC_VOUCHER_TRACE.REF_SER, MISC_VOUCHER_TRACE.TRAN_ID__REF,"+
					"SUM(MISC_VOUCHER_TRACE.AMOUNT) AS AMOUNT, MISC_VOUCHER_TRACE.TAX_CODE,MISC_VOUCHER_TRACE.TRAN_DATE,"+
					"MISC_VOUCHER_TRACE.SUNDRY_TYPE,MISC_VOUCHER_TRACE.SUNDRY_CODE,MISC_VOUCHER_TRACE.TRAN_ID__SER,"+
					"(CASE WHEN MISC_VOUCHER.REMARKS IS NULL THEN VOUCHER.REMARKS ELSE MISC_VOUCHER.REMARKS END)"+
					" MISC_VOUCHER_REMARKS,TAX.TAX_GROUP FROM MISC_VOUCHER_TRACE,VOUCHER, MISC_VOUCHER,TAX"+
					" WHERE ( MISC_VOUCHER_TRACE.TRAN_ID__REF = VOUCHER.TRAN_ID (+)) AND"+
					"( MISC_VOUCHER_TRACE.TRAN_ID__REF = MISC_VOUCHER.TRAN_ID (+)) AND "+
					"( MISC_VOUCHER_TRACE.TAX_CODE = TAX.TAX_CODE ) AND  "+
					" ( ( MISC_VOUCHER_TRACE.TRAN_ID = '"+tranId+"' ) AND "+
					"( MISC_VOUCHER_TRACE.TRAN_ID__SER IS NULL ) )"+
					" GROUP BY MISC_VOUCHER_TRACE.TRAN_ID,"+
					"MISC_VOUCHER_TRACE.REF_SER,MISC_VOUCHER_TRACE.TRAN_ID__REF,"+
					"MISC_VOUCHER_TRACE.TAX_CODE, MISC_VOUCHER_TRACE.TRAN_DATE,"+
					"MISC_VOUCHER_TRACE.SUNDRY_TYPE,MISC_VOUCHER_TRACE.SUNDRY_CODE,"+
					"MISC_VOUCHER_TRACE.TRAN_ID__SER,"+
					"(CASE WHEN MISC_VOUCHER.REMARKS IS NULL THEN VOUCHER.REMARKS ELSE MISC_VOUCHER.REMARKS END),"+
					"TAX.TAX_GROUP ORDER BY MISC_VOUCHER_TRACE.SUNDRY_TYPE ASC, MISC_VOUCHER_TRACE.SUNDRY_CODE ASC,"+
					"MISC_VOUCHER_TRACE.TRAN_DATE ASC ";
				System.out.println("Executing SQL :: "+sql);
				rs = stmt.executeQuery(sql);
				cnt = 0;
				while(rs.next())
				{
					retString.append(rs.getString(1)).append("\t");
					retString.append(rs.getString(2)).append("\t");
					retString.append(rs.getString(3)).append("\t");
					retString.append(rs.getString(4)).append("\t");
					retString.append(rs.getString(5)).append("\t");
					retString.append(rs.getString(6)).append("\t");
					retString.append(rs.getString(7)).append("\t");
					retString.append(rs.getString(8)).append("\t");
					retString.append(rs.getString(9)).append("\t");
					retString.append(rs.getString(10)).append("\t");
					retString.append(rs.getString(11)).append("\n");
					cnt++;
				}
				System.out.println("No Of Records ::"+cnt);
			}
			else
			{
			   ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			   errString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);
			   conn.close();
			   return errString;
			}				
		}
		catch(Exception e)
		{
			System.out.println("Exception in MiscVouchTdsEJB ::"+e.getMessage());
			e.printStackTrace();
		}
		finally
		{
			System.out.println("Closing Connection....");
			try
			{
				conn.close();
				conn = null;
			}catch(Exception se){}
		}
		return retString.toString();
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		Document dom1 = null,dom2 = null;
		String retString = "";
		System.out.println("In Process Logic....[MiscVouchTdsEJB]");
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			dom1 = genericUtility.parseString(xmlString);
			dom2 = genericUtility.parseString(xmlString2);
			retString = process(dom1,dom2,windowName,xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception ::MiscVouchTdsEJB :: process() Method :: "+e.getMessage());
			throw new ITMException(e);
		}
		return retString;
	}
	public String process(Document dom, Document dom2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		String sql = "";
		String env = "",errCode = "",xmlString = "",retString = "";
		int cnt = 1,printCnt = 0,detLen = 0,detRec = 0,posted = 0,upd = 0;
		NodeList detailNodes = null,childNodes = null;
		Node child = null;
		String nodeName = "",nodeValue = "";

		String syndryType = "",syndryCode = "",tranID = "",refSeries = "";
		String tranIDRef = "",taxCode = "",taxGroup = "",siteCode = "",keystr = "";
		String SundryTypeOld = "",sundryCodeOld = "",tranDate = "",tranIDSer = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		try
		{
			java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(genericUtility.getApplDateFormat()); 
			conn = connDriver.getConnectDB("DriverITM");
			stmt = conn.createStatement();
			env = itmDBAccessEJB.getEnvFin("999999","TDSPRN",conn);
			if (env.equalsIgnoreCase("NULLFOUND"))
			{
				errCode = "TDSPRN";
			}
			else
			{
				printCnt = Integer.parseInt(env);
				if (printCnt == 0)
				{
					errCode = "TDSPRN";
				}
			}
			if (errCode.equals(""))
			{
				detailNodes = dom2.getElementsByTagName("Detail2");
				detLen = detailNodes.getLength();
				for (int i=0;i < detLen ;i++ )
				{
					child = detailNodes.item(i);
					childNodes = child.getChildNodes();
					detRec = childNodes.getLength();
					for (int j =0;j < detRec;j++ )
					{
						nodeName = childNodes.item(j).getNodeName();
						if (nodeName.equalsIgnoreCase("sundry_type"))
						{
							syndryType = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("sundry_code"))
						{
							syndryCode = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("tran_id"))
						{
							tranID = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("ref_ser"))
						{
							refSeries = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("tran_id__ref"))
						{
							tranIDRef = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("tax_code"))
						{
							taxCode = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("tax_group"))
						{
							taxGroup = childNodes.item(j).getFirstChild().getNodeValue().trim();
						}
						if (nodeName.equalsIgnoreCase("tran_date"))
						{
							tranDate = childNodes.item(j).getFirstChild().getNodeValue().trim();
							tranDate = genericUtility.getValidDateString(tranDate,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
						}
					} 
					
					if (!syndryType.equalsIgnoreCase(SundryTypeOld) || !syndryCode.equalsIgnoreCase(sundryCodeOld) && cnt >= printCnt)
					{
						cnt = 1;
						sql = "SELECT SITE_CODE FROM MISC_VOUCHER WHERE TRAN_ID = '"+tranID+"'";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							siteCode = rs.getString("SITE_CODE");
							if (siteCode == null)
							{
								errCode = "VMVOUC4";
								break;
							}
						}
						else
						{
							errCode = "VMVOUC4";
							break;
						}
						sql = "SELECT KEY_STRING FROM TRANSETUP WHERE TRAN_WINDOW = 'w_misc_voucher_trace'";
						rs = stmt.executeQuery(sql);
						if (rs.next())
						{
							keystr = rs.getString("KEY_STRING");
							if (keystr == null)
							{
								errCode = "VTSEQ";
								break;
							}
						}
						else
						{
							errCode = "VTSEQ";
							break;
						}
						xmlString = "<Detail1>"+
									"<tax_code>"+taxCode+"</tax_code>"+
									"<tran_date>"+tranDate+"</tran_date>"+
									"<site_code>"+siteCode+"</site_code>"+									
									"<tax_group>"+taxGroup+"</tax_group>"+
									"</Detail1>";
						System.out.println("XMLString for TranIDGenerator :: \n"+xmlString);
						TransIDGenerator  tg = new TransIDGenerator(xmlString,"Base","oracle");
						tranIDSer = tg.generateTranSeqID("MTRACE","TRAN_ID",keystr,conn);
						System.out.println("Generated Key :: "+tranIDSer);
						if (tranIDSer.indexOf("ERROR") > -1 )
						{
							errCode = "VTTRANID";
							break;
						}
					}
					else
					{
						cnt++;
					}
					sql = "UPDATE MISC_VOUCHER_TRACE SET TRAN_ID__SER = '"+tranIDSer+"' WHERE TRAN_ID = '"
						+tranID+"' AND REF_SER = '"+refSeries +"' AND TRAN_ID__REF = '"+tranIDRef+"'";
					System.out.println("Update SQL :: "+sql);
					upd = stmt.executeUpdate(sql);
					if (upd == 0)
					{
						errCode = "DS000NR";
						break;
					}
					SundryTypeOld =  syndryType;
					sundryCodeOld =  syndryCode;
					posted++;
				} //End for
			}//Enf if
			if (errCode != null && errCode.length() > 0)
			{
				conn.rollback();
				retString = itmDBAccessEJB.getErrorString("",errCode,"","",conn);				
			}
			else
			{
				conn.commit();
				retString = itmDBAccessEJB.getErrorString("","VTSUCC","","",conn);				
			}
		}//End try
		catch(SQLException se)
		{
			System.out.println("SQLException :: "+se.getMessage());
			throw new ITMException(se);
		}
		catch(Exception e)
		{
			System.out.println("Exception in MiscVouchTdsEJB :: Process :: "+e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				System.out.println("Closing Connection.....");
				conn.close();
				conn = null;
			}catch(Exception se){}
		}
		return retString;
	}	
};