package ibase.webitm.ejb.fin;
import ibase.webitm.utility.*;
import ibase.utility.CommonConstants;
import ibase.webitm.ejb.*;
import ibase.system.config.*;
import java.rmi.RemoteException;
import java.text.*;
import java.util.*;
import java.sql.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.ejb.*;
import javax.naming.InitialContext;
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import ibase.webitm.ejb.fin.FinCommon;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3

public class GenerateTDSPrc extends ProcessEJB implements GenerateTDSPrcLocal,GenerateTDSPrcRemote //SessionBean
{
	Connection conn = null;
	String errorString = null;
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	/*public void ejbCreate() throws RemoteException, CreateException 
	{
		System.out.println("Create Method Called....");
	}
	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("GenerateTDSPrcEJB :getData() function called");
		String rtrStr = "";
		Document headerDom = null;
		Document detailDom = null;		
		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 :GenerateTDSPrcEJB :getData(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			rtrStr = e.getMessage();			
		}
		return rtrStr; 
	}//END OF GETDATA(1)

	public String getData(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String errString="";		
		String errCode = "";
		String getDataSql= "" ;
		String sql= "",sql1 ="",tranId="" ;
		String resultString = "",vouchType="";
		ResultSet rs = null,rs1 = null;
		PreparedStatement pstmt = null;
		Statement st = null;
		StringBuffer retTabSepStrBuff = new StringBuffer();		
		String taxGroup="",sundryName="";
		String 	refSer="",tranIdRef="",taxCode="",sundryType="",sundryCode="",tranIdSer="",miscVoucherRemarks="",voucherRemarks="",remarks="";
		int count=0;
		double amount =0.0d;
		java.sql.Timestamp tranDate =null;
		ConnDriver connDriver = new ConnDriver();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
		}
		catch (Exception e)
		{
			System.out.println("Exception :GenerateTDSPrcEJB :ejbCreate :==>"+e);			
			e.printStackTrace();
		} 		
		try
		{
			tranId = genericUtility.getColumnValue("tran_id",headerDom);
			if(tranId !=null && tranId.equals(""))
			{
				tranId = "";
				System.out.println("tranId  is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","");
				return errString;
			}
			if ( tranId == null || tranId.trim().length() == 0 )
			{
				tranId = "";
				System.out.println("tranId  From is Null...");
				errString = itmDBAccessEJB.getErrorString("","VTMRPPARM","");
				return errString;
			} 
			System.out.println("tranId..............."+tranId);	

			sql = "select vouch_type from misc_voucher where tran_id = '"+tranId+"'";
			System.out.println(" sql.................... "+sql);
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				vouchType = rs.getString("VOUCH_TYPE");				
			}													
			if (!vouchType.equalsIgnoreCase("T"))
			{
				errString = itmDBAccessEJB.getErrorString("","VTVOUCH3","");
				return errString;
			}
			System.out.println("Voucher Type :: "+vouchType);

			sql1 = "SELECT count(*)   "+
			       "FROM misc_voucher_trace  WHERE tran_id = '"+tranId+"' AND tran_id__ser is null ";
			System.out.println("sql1..............."+sql1);
			pstmt = conn.prepareStatement(sql1);
			rs = pstmt.executeQuery();
			if (rs.next())
			{
				count = rs.getInt(1);
			}
			rs.close();
			pstmt.close();
			if( count == 0)
			{
				errString = itmDBAccessEJB.getErrorString("","VTNOREC","");
				return errString;
			}

			getDataSql = "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, "
						+" MISC_VOUCHER.REMARKS,   "
						+" VOUCHER.REMARKS,"
						+" TAX.TAX_GROUP "
						+" ORDER BY MISC_VOUCHER_TRACE.SUNDRY_TYPE ASC, "
						+" MISC_VOUCHER_TRACE.SUNDRY_CODE ASC "	;

			System.out.println("getDataSql..............."+getDataSql);           
			pstmt = conn.prepareStatement(getDataSql);			
			rs = pstmt.executeQuery();
			while(rs.next())
			{
					retTabSepStrBuff.append(rs.getString(1)).append("\t");
					retTabSepStrBuff.append(rs.getString(2)).append("\t");
					retTabSepStrBuff.append(rs.getString(3)).append("\t");
					retTabSepStrBuff.append(rs.getString(4)).append("\t");
					retTabSepStrBuff.append(rs.getString(5)).append("\t");
					retTabSepStrBuff.append(rs.getString(6)).append("\t");
					retTabSepStrBuff.append(rs.getString(7)).append("\t");
					retTabSepStrBuff.append(rs.getString(8)).append("\t");
					retTabSepStrBuff.append(rs.getString(9)).append("\t");
					retTabSepStrBuff.append(rs.getString(10)).append("\t");
					retTabSepStrBuff.append(rs.getString(11)).append("\n");
			}
			resultString = retTabSepStrBuff.toString();
			System.out.println("ResultString....." + resultString);
			rs.close();
			pstmt.close();

		}
		catch (SQLException e)
		{
			System.out.println("SQLException :GenerateTDSPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		catch (Exception e)
		{
			System.out.println("Exception :GenerateTDSPrcEJB :getData(Document headerDom, Document detailDom, String windowName, String xtraParams):" + e.getMessage() + ":");
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				retTabSepStrBuff = null;
				if(conn != null)
				{					
					if(pstmt != null)
					{
						pstmt.close();
						pstmt=null;
					}
					conn.close();
				}
			}
			catch(Exception e)
			{
				errString = e.getMessage();
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return resultString;	
	}//END OF GETDATA(2)
	
	public String process() throws RemoteException,ITMException
	{
		return "";
	}
	public String process(String xmlString, String xmlString2, String windowName, String xtraParams)
		throws RemoteException,ITMException
	{
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		String retStr = "";
		
		
		try
		{				
				System.out.println("xmlString[process]::::::::::;;;"+xmlString);
				System.out.println("xmlString2[process]::::::::::;;;"+xmlString2);
				System.out.println("windowName[process]::::::::::;;;"+windowName);
				System.out.println("xtraParams[process]:::::::::;;;"+xtraParams);
				
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
	
		try
		{	
			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);
			}
			retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{			
			System.out.println("Exception :GenerateTDSPrcEJB :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			retStr = e.getMessage();
		}
		return retStr;
	}//END OF PROCESS (1)

	
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "" ,sql1 = "",errString = "";
        String retString = "" ,errCode = "";
		String 	sundryTypeOld = ""; 
		String 	sundryCodeOld = ""	,tranid_ser="",env="",tranDateStr=""; 
		String 	sundryType="",sundryCode="",tranId="",refSer="",tranIdRef="",taxCode="",taxGroup="";
		Timestamp tranDate =null;
		ConnDriver connDriver = new ConnDriver();
		int parentNodeListLength = 0;
		int childNodeListLength = 0;
		String childNodeName = "";
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null; 	
		String siteCode = null;
		int printCnt=0,cnt =0,upd=0;
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);				
		}
		catch (Exception e)
		{
			System.out.println("Exception :WorkorderPrcEJB :ejbCreate :==>"+e);	
			e.printStackTrace();
		} 
		try
		{	 
			FinCommon finCommon = new FinCommon();
			env = finCommon.getFinparams("999999", "TDSPRN",conn);
			if(env.equalsIgnoreCase("NULLFOUND"))
			{
				System.out.println("NULLFOUND..........");
				errString = itmDBAccessEJB.getErrorString("","TDSPRN","");
				return errString;
			}
			else
			{
				printCnt =Integer.parseInt(env);
				if(printCnt ==0)
				{
					System.out.println("if(printCnt ==0)..........");
					errString = itmDBAccessEJB.getErrorString("","TDSPRN","");
					return errString;
				}					
			}
			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+"\n");
				for (int childRow = 0; childRow < childNodeListLength; childRow++)
				{
					
					childNode = childNodeList.item(childRow);
					childNodeName = childNode.getNodeName();
					if (childNodeName.equals("sundry_type"))
					{
						sundryType = childNode.getFirstChild().getNodeValue();
					}	
					if (childNodeName.equals("sundry_code"))
					{
						sundryCode = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tran_id"))
					{
						tranId = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("ref_ser"))
					{
						refSer = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tran_id__ref"))
					{
						tranIdRef = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tax_code"))
					{
						taxCode = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tax_group"))
					{
						taxGroup = childNode.getFirstChild().getNodeValue();
					}
					if (childNodeName.equals("tran_date"))
					{
						tranDateStr = childNode.getFirstChild().getNodeValue();
						tranDateStr = genericUtility.getValidDateString(tranDateStr,genericUtility.getDBDateFormat(),genericUtility.getApplDateFormat());
					}
				}//inner for loop
				System.out.println("taxGroup..............."+taxGroup);
				System.out.println("taxCode..............."+taxCode);
				System.out.println("tranDateStr..............."+tranDateStr);

				if(!sundryCode.equalsIgnoreCase(sundryCodeOld)|| (!sundryType.equalsIgnoreCase(sundryTypeOld)) || (cnt >= printCnt ) )
				{
				   ///if different suntry_type and code then generate a different tran_id
				   cnt = 1 ;
				   sql1 = "SELECT site_code  "+
						 "FROM misc_voucher  WHERE tran_id = '"+tranId+"'  ";
					System.out.println("sql1..............."+sql1);
					pstmt = conn.prepareStatement(sql1);
					rs = pstmt.executeQuery();
					if (rs.next())
					{
						siteCode = rs.getString(1);
						if(siteCode ==null)
						{
							errString = itmDBAccessEJB.getErrorString("","VMVOUC4","");
							return errString;
						}
					}
					else
					{
						errString = itmDBAccessEJB.getErrorString("","VMVOUC4","");
						return errString;
					}
					rs.close();
					pstmt.close();
					tranid_ser = generateTranId("W_MISC_VOUCHER_TRACE",tranDateStr,siteCode,conn);
					if(tranid_ser == null || tranid_ser.trim().length() ==0)
					{
						//System.out.println("errcode......"+errCode);
						errString = itmDBAccessEJB.getErrorString("","VTTRANID","");
						return errString;
					}
				}
				else
				{
					cnt++;
				}
				sql ="update misc_voucher_trace set tran_id__ser = '"+tranid_ser+"'   "
					+"where tran_id = '"+tranId+"' and  ref_ser ='"+refSer+"'  and  tran_id__ref ='"+tranIdRef+"' " ;
				System.out.println("sql.................. :"+sql);
				pstmt = conn.prepareStatement(sql);			
				upd = pstmt.executeUpdate();
				if(upd > 0)
				{
					System.out.println("recoed updated "+upd);
				}
				else
				{
					System.out.println("recoed not updated "+upd);
				}
				pstmt.close();
				pstmt =null;
				sundryCodeOld = sundryCode;		 
				sundryTypeOld = sundryType;
			}//end for loop
		}
	   	catch(Exception e)
		{
			   System.out.println("Exception in.GenerateTDSPrcEJB..."+e.getMessage());
			   e.printStackTrace();
			   errString = e.getMessage();
		}
		finally
		{
			try
			{		
				if(errString.trim().length() > 0)
				{
					conn.rollback();
					System.out.println(" Rollback connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTPROUNSUC","");
				}
				else
				{
					conn.commit();
					System.out.println(" commiting connection.............");
					errString = itmDBAccessEJB.getErrorString("","VTCONF","");
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt =null;
				}
				if(conn != null)
				{
					conn.close();
					conn = null;
				}	
			}
			catch(Exception e)
			{
			   System.out.println("Error In closing connection::==> "+e);
		       e.printStackTrace();
			}
		}
		System.out.println("returning from  genTDS   "+errString);
	    return (errString);
	}
 private String generateTranId(String windowName,String tranDate,String siteCode,Connection conn)
 {
	
		Statement stmt = null;
		ResultSet rs = null;
		String sql = null;
		String tranId = null;
		String xmlValues = null;
		 try
	     {
	    	sql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE UPPER(TRAN_WINDOW)= '"+windowName+"'";
	    	System.out.println("Tran generator Sql"+sql);
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			String tranSer1 = "";
			String keyString = "";
			String keyCol = "";
			if (rs.next())
			{
				keyString = rs.getString(1);
				keyCol = rs.getString(2);
				tranSer1 = rs.getString(3);				
			}
			System.out.println("keyString :"+keyString);
			System.out.println("keyCol :"+keyCol);
			System.out.println("tranSer1 :"+tranSer1);
			xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
			xmlValues = xmlValues + "<Header></Header>";
			xmlValues = xmlValues + "<Detail1>";
			xmlValues = xmlValues +	"<tran_id></tran_id>";
			xmlValues = xmlValues + "<site_code>" + siteCode + "</site_code>";
			xmlValues = xmlValues + "<tran_date>"+ tranDate + "</tran_date>";
			xmlValues = xmlValues + "</Detail1></Root>";
			System.out.println("xmlValues  :["+xmlValues+"]");
			TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
			tranId = tg.generateTranSeqID(tranSer1, keyCol, keyString, conn);
			System.out.println("tranId :"+tranId);
		}
		catch (SQLException ex)
		{
			ex.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return tranId;
	}
	private String getCurrdateInAppFormat()
	{
		String currAppdate =null;
		java.sql.Timestamp currDate = null;
		Object date = null;
		SimpleDateFormat DBDate=null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{				
				currDate =new java.sql.Timestamp(System.currentTimeMillis()) ;
				System.out.println(genericUtility.getDBDateFormat());
				DBDate= new SimpleDateFormat(genericUtility.getDBDateFormat());
				date = DBDate.parse(currDate.toString());
				currDate =	java.sql.Timestamp.valueOf(DBDate.format(date).toString() + " 00:00:00.0");
				currAppdate = new SimpleDateFormat(genericUtility.getApplDateFormat()).format(currDate).toString();
		}
		catch(Exception e)
		{
		
			System.out.println("Exception in  getCurrdateInAppFormat:::"+e.getMessage());
		}
		genericUtility = null;
		return (currAppdate);
	}

}