/*
    Window Name : w_ddetail
*/

package ibase.webitm.ejb.fin;

import java.rmi.RemoteException;
import java.util.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import javax.ejb.*;
import javax.naming.InitialContext;

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

@Stateless // added for ejb3

public class DDetailPrc extends ProcessEJB implements DDetailPrcLocal ,DDetailPrcRemote // SessionBean
{
	String paymentNo = "";
	String fileName = "";
	String ddStartNo = "";

	GenericUtility genericUtility = GenericUtility.getInstance();

  	/*public void ejbCreate() throws RemoteException, CreateException
	{
		try
		{
			System.out.println("DDetailPrcEJB ejbCreate called.........");

		}
		catch (Exception e)
		{
			System.out.println("Exception :DDetailPrcEJB :ejbCreate :==>"+e);
			throw new CreateException();
		}
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate()
	{
	}
	public void ejbPassivate()
	{
	}
	public String process() throws RemoteException,ITMException
	{
		return "";
	}*/

	public String getData(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if(xmlString != null && xmlString.trim().length()!=0 )
			{
				System.out.println("XML String :::-:"+xmlString);
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				System.out.println("XML String :::-:"+xmlString2);
				detailDom = genericUtility.parseString(xmlString2);
			}
			rtrStr = getData(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :DDetailPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		return rtrStr;
	}
	//getData()
	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String errCode = "";
		String errString = "";
		String resultString = "";;
		String countSql1="";
		String countSql2="";
		String getDataSql= "";
		String tempString = null;
		Connection conn = null;
		ResultSet rsCnt1 = null;
		ResultSet rsCnt2 = null;
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		Statement st = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();
		int count = 0,cnt = 0,size = 0,newSize,diff;
	    ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		System.out.println("xtraParams $$$$$$$$$$$$$$$$$$$$$$$$ "+xtraParams);
		String userId = "";
		userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"userId");
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			paymentNo = genericUtility.getColumnValue("payment_no",headerDom);
			if ( paymentNo == null || paymentNo.trim().length() == 0 )
			{
				paymentNo = "";
				errString = itmDBAccessEJB.getErrorString("","VEPAY1","","",conn);
				return errString;
			}
			System.out.println("PAYMENT NO.................. :"+ paymentNo);
			ddStartNo = genericUtility.getColumnValue("dd_start__no",headerDom);
			if ( ddStartNo == null || ddStartNo.equals("null") || ddStartNo.trim().length() == 0 )
			{
				ddStartNo = "";
				errString = itmDBAccessEJB.getErrorString("","NLDDS","","",conn);
				return errString;
			}
			System.out.println("DD Strat NO.................. :"+ ddStartNo);
			size = ddStartNo.trim().length();
			System.out.println("The length of DD Strat NO is  :"+ size);

			fileName = genericUtility.getColumnValue("file_name",headerDom);

			System.out.println("File Name is............................:"+fileName);
			st = conn.createStatement();

			countSql1 = "SELECT COUNT(1) AS COUNT FROM MISC_PAYMENT WHERE TRAN_ID='"+paymentNo+"'";
			System.out.println("FIRST COUNT SQL IS......."+ countSql1);
			rsCnt1 = st.executeQuery(countSql1);
			if(rsCnt1.next())
			{
				count = rsCnt1.getInt("COUNT");
			}
			if(count == 0)
			{
				System.out.println("NOT A VALID PAYMENT NO."+paymentNo);
				errCode = "VTPAY3";
				errString = itmDBAccessEJB.getErrorString("payment_no",errCode,userId);
				return errString;
			}
			countSql2 = "SELECT COUNT(1) AS COUNT FROM MISC_PAYMENT WHERE TRAN_ID='"+paymentNo +"'"
					  +	"AND CONFIRMED ='Y' AND (PAY_MODE = 'D' OR PAY_MODE = 'P')";
			System.out.println("SECOND COUNT SQL IS......."+ countSql2);
		  	rsCnt2 = st.executeQuery(countSql2);
			if(rsCnt2.next())
			{
				cnt = rsCnt2.getInt("COUNT");
			}
			if(cnt == 1)
			{
				System.out.println("TRANSACTION IS CONFIRMED.........");

				getDataSql=	"SELECT MISC_PAYDET.TRAN_ID,"
						  + "MISC_PAYDET.TRAN_SER,MISC_PAYDET.VOUCH_NO,"
				   		  +	"MISC_PAYDET.VOUCH_DATE,MISC_PAYDET.NET_AMT,"
				   		  +	"MISC_PAYDET.PAY_AMT,MISC_PAYDET.CURR_CODE,"
				  		  +	"MISC_PAYDET.EXCH_RATE__VOUCH,"
				  		  +	"MISC_PAYDET.DIFF_AMT__EXCH,MISC_PAYDET.ACCT_CODE__AP,"
				   	   	  +	"MISC_PAYDET.CCTR_CODE__AP,ACCOUNTS.DESCR,"
				   	   	  +	"MISC_PAYDET.SUNDRY_TYPE,MISC_PAYDET.SUNDRY_CODE,MISC_PAYDET.INSTR_NO,"
				   		  +	"MISC_PAYDET.INSTR_DATE,MISC_PAYDET.DRAWN_AT,"
				   		  +	"MISC_PAYDET.BANK_CHARGES,FN_SUNDRY_NAME(MISC_PAYDET.SUNDRY_TYPE,MISC_PAYDET.SUNDRY_CODE,'F') SUNDRY_NAME,MISC_PAYDET.DESPATCH_DATE,MISC_PAYDET.LINE_NO "
				  		  +	"FROM MISC_PAYDET,ACCOUNTS "
				   		  +	"WHERE (MISC_PAYDET.ACCT_CODE__AP = ACCOUNTS.ACCT_CODE) AND "
				   	   	  +	"MISC_PAYDET.TRAN_ID = '"+paymentNo+"' ORDER BY LINE_NO ";
				pstmt = conn.prepareStatement(getDataSql);

				System.out.println("The getDataSql becomes .................:"+getDataSql);
				rs = pstmt.executeQuery();

           		while (rs.next())
				{
					/*
					tran_id ,
		           tran_ser ,
		           vouch_no ,
		           vouch_date ,
		           net_amt ,
		           pay_amt ,
		           curr_code ,
		           exch_rate__vouch ,
		           diff_amt__exch ,
		           acct_code__ap ,
		           cctr_code__ap ,
		           descr ,
		           sundry_type ,
		           sundry_code ,
		           instr_no ,
		           instr_date ,
		           drawn_at ,
		           bank_charges ,
		           sundry_name,
		           despatch_date
					line_no
					*/
					//TRAN_ID
					retTabSepStrBuff.append(rs.getString(1)).append("\t");
					//TRAN_SER
					retTabSepStrBuff.append(rs.getString(2)).append("\t");
					//VOUCH_NO
					retTabSepStrBuff.append(rs.getString(3)).append("\t");
					//VOUCH_DATE
					retTabSepStrBuff.append(rs.getDate(4)).append("\t");
					//NET_AMT
					retTabSepStrBuff.append(rs.getDouble(5)).append("\t");
					//PAY_AMT
					retTabSepStrBuff.append(rs.getDouble(6)).append("\t");
					//CURR_CODE
					retTabSepStrBuff.append(rs.getString(7)).append("\t");
					//EXCH_RATE__VOUCH
					retTabSepStrBuff.append(rs.getDouble(8)).append("\t");
					//DIFF_AMT__EXCH
					retTabSepStrBuff.append(rs.getDouble(9)).append("\t");
					//ACCT_CODE__AP
					retTabSepStrBuff.append(rs.getString(10)).append("\t");
					//CCTR_CODE__AP
					retTabSepStrBuff.append(rs.getString(11)).append("\t");
					//DESCR
					retTabSepStrBuff.append(rs.getString(12)).append("\t");
					//SUNDRY_TYPE
					retTabSepStrBuff.append(rs.getString(13)).append("\t");
					//SUNDRY_CODE
					retTabSepStrBuff.append(rs.getString(14)).append("\t");
					//INSTR_NO
					String instr = rs.getString(15);
					retTabSepStrBuff.append(ddStartNo).append("\t");
					//INSTR_DATE
					tempString = rs.getString(16);
					if ( tempString == null || tempString.equals("null") || tempString.trim().length() == 0 )
					{
						retTabSepStrBuff.append("").append("\t");
					}
					else
					{
						retTabSepStrBuff.append(tempString).append("\t");
					}
					//DRAWN_AT
					tempString = rs.getString(17);
					if ( tempString == null || tempString.equals("null") || tempString.trim().length() == 0 )
					{
						retTabSepStrBuff.append("").append("\t");
					}
					else
					{
						retTabSepStrBuff.append(tempString).append("\t");
					}
					//BANK_CHARGES
					retTabSepStrBuff.append(rs.getDouble(18)).append("\t");
					//SUNDRY_NAME
					retTabSepStrBuff.append(rs.getString(19)).append("\t");
					//DESPATCH_DATE
					tempString = rs.getString(20);
					if ( tempString == null || tempString.equals("null") || tempString.trim().length() == 0 )
					{
						retTabSepStrBuff.append("").append("\t");
					}
					else
					{
						retTabSepStrBuff.append(tempString).append("\t");
					}

					//LINE_NO
					retTabSepStrBuff.append(rs.getInt(21)).append("\t");
					retTabSepStrBuff.append("\n");
					int ddNo = Integer.parseInt(ddStartNo);
					++ddNo;
					ddStartNo = Integer.toString(ddNo);

					newSize = ddStartNo.trim().length();
					diff = (size - newSize);

					StringBuffer sb = new StringBuffer();
					for(int zero=0;zero<diff;zero++)
					sb.append("0");
					ddStartNo =  (new StringBuffer(ddStartNo).insert(0,sb.toString())).toString();

					System.out.println("DD Start No :::-"+ddStartNo);
				}//while
			}//if
			else
			{
				errCode = "VTPAY3";
				errString = itmDBAccessEJB.getErrorString("payment_no",errCode,userId);
				return errString;
			}//else

			resultString = retTabSepStrBuff.toString();
			if (!errCode.equals(""))
			{
				resultString = itmDBAccessEJB.getErrorString("", errCode, "", "", conn);
				System.out.println("resultString.........: " + resultString);
			}
		}//try
		catch (SQLException e)
		{
			System.out.println("SQLException :DDetailPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :DDetailPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception e)
			{}
		}
		return resultString;
	}
	//process()
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		System.out.println("xmlString :::"+ xmlString);
		System.out.println("xmlString2 :::"+ xmlString2);
		GenericUtility genericUtility = GenericUtility.getInstance();
		System.out.println("below genericUtility :::-");
		try
		{
			System.out.println("inside try1 block :::");
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
				System.out.println("headerDom " + headerDom);
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
				System.out.println("detailDom " + detailDom);
			}
			System.out.println("windowName" + windowName);
			System.out.println("xtraParams" + xtraParams);
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :DDetailPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;
	}
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		System.out.println("DetailDom ::"+ detailDom);
		String childNodeName = "";
		String instrNo = "";
		String instrDate = "";
		String despatchDate = "";
		String lineNo = "";
		String errCode = "";
		String errString = "";
		String updateSql = "";
		String drawnAt = null;
		Connection conn = null;
		Statement st = null;
		PreparedStatement pstmt = null;
		java.sql.Timestamp instr_Date =  null;

		int lineNumber = 0;
		int updCnt = 0;
		int parentNodeListLength = 0;
		int childNodeListLength = 0;

		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		boolean flag = false;

	    ConnDriver connDriver = new ConnDriver();
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();

		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			parentNodeList = detailDom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();
			System.out.println("ParentNodeListLength ..........."+parentNodeListLength);

			for (int selectedRow = 0; selectedRow < parentNodeListLength; selectedRow++)
			{
				parentNode = parentNodeList.item(selectedRow);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				System.out.println("ChildNodeListLength ........."+ childNodeListLength);
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();

					if (childNodeName.equals("instr_no"))
					{
						instrNo = (childNode.getFirstChild().getNodeValue());
						System.out.println("InstrNo ........."+ instrNo);
					}
					if (childNodeName.equals("instr_date"))
					{
						instrDate = (childNode.getFirstChild().getNodeValue());
						System.out.println("InstrDate ........ "+ instrDate);

						if ( instrDate == null || instrDate.equals("null") || instrDate.trim().length() == 0 )
						{
							instrDate = "";
							System.out.println("InstrDate is null.............");
							errString = itmDBAccessEJB.getErrorString("","VEDAT2","","",conn);
							return errString;
						}
					}
					if (childNodeName.equals("line_no"))
					{
						lineNo = (childNode.getFirstChild().getNodeValue());
						System.out.println("LineNo ..........."+ lineNo);
						lineNumber=Integer.parseInt(lineNo);
						System.out.println("LineNo ............"+ lineNumber);
					}
					if (childNodeName.equals("despatch_date"))
					{
						despatchDate = (childNode.getFirstChild().getNodeValue());
						System.out.println("DespatchDate ........ "+ despatchDate);

						if ( despatchDate == null || despatchDate.trim().equalsIgnoreCase("null") || despatchDate.trim().equalsIgnoreCase("nul") || despatchDate.trim().length() == 0 )
						{
							despatchDate = "";
							System.out.println("DespatchDate is null.............");
						}
					}
					// 05-01-2007 manoharan drawn_at added for update
					if (childNodeName.equals("drawn_at"))
					{
						drawnAt = (childNode.getFirstChild().getNodeValue());
						System.out.println("drawnAt ..........."+ drawnAt);
					}
					// end 05-01-2007 manoharan drawn_at added for update
				}
				// 05-01-2007 manoharan drawn_at added for update
				updateSql = "UPDATE MISC_PAYDET  SET INSTR_NO = '"+ instrNo +"', INSTR_DATE = ?,DESPATCH_DATE = ?, "
					  	  + "DRAWN_AT = ? WHERE TRAN_ID = '"+ paymentNo +"' AND LINE_NO = "+ lineNumber;
				// end 05-01-2007 manoharan
				pstmt = conn.prepareStatement(updateSql);

				if(instrDate.trim().length() == 0)
				{
					pstmt.setNull(1,java.sql.Types.TIMESTAMP);
				}
				else
				{
					instrDate = genericUtility.getValidDateString(instrDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
					pstmt.setTimestamp(1,java.sql.Timestamp.valueOf(instrDate +" 00:00:00"));
				}

				if(despatchDate.trim().length() == 0)
				{
					pstmt.setNull(2,java.sql.Types.TIMESTAMP);
				}
				else
				{
					despatchDate = genericUtility.getValidDateString(despatchDate, genericUtility.getApplDateFormat(), genericUtility.getDBDateFormat());
					pstmt.setTimestamp(2,java.sql.Timestamp.valueOf(despatchDate +" 00:00:00"));
				}
				// 05-01-2007 manoharan drawn_at added for update
				pstmt.setString(3,drawnAt);
				// end 05-01-2007 manoharan drawn_at added for update
				updCnt = pstmt.executeUpdate();

				System.out.println("updateSql..........."+ updateSql);
				System.out.println("No of records updated "+updCnt);

				if(updCnt>0)
				{
					flag = true;
					//return errString;
				}
				else
				{
					errString= itmDBAccessEJB.getErrorString("","VTADHOC1","","",conn);
					return errString;
				}
			}
			if(flag)
			{
				System.out.println("RECORD UPDATED SUCCESSFULLY..................");
				errString= itmDBAccessEJB.getErrorString("","VTUPD1","","",conn);
				conn.commit();
			}
		}//try end
		catch(Exception e)
		{
			System.out.println("Exception :DDetailPrcEJB ::" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			System.out.println("Closing Connection2....");
			try
			{
				conn.close();
				conn = null;
			}
			catch(Exception se){}
		}
		System.out.println("errString: "+errString);
		return errString;
	}
}
