package ibase.webitm.ejb.wms;


import java.sql.*;
import java.rmi.RemoteException;
import org.w3c.dom.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;

import javax.ejb.Stateless;

import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;

@Stateless
public class LpnNoGenPrc  extends ProcessEJB implements LpnNoGenPrcLocal,LpnNoGenPrcRemote

{
	String siteCode = "";
	String labelType = "";
	String labelID = "";
	String keyString = "";
	String tranIDCol = "";
	String refSer = "";
	String retString = "";

	
	public String process() throws RemoteException,ITMException
	{
		return "";
	}

	public String process(String xmlString, String xmlString2, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String retStr = "";
		Document detailDom = null;
		Document headerDom = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("xmlString   ["+xmlString+"]");
			System.out.println("xmlString2  ["+xmlString2+"]");
			System.out.println("windowName   ["+windowName+"]");
			System.out.println("xtraParams   ["+xtraParams+"]");
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				headerDom = genericUtility.parseString(xmlString);
			}
			if(xmlString2 != null && xmlString2.length()!=0)
			{
				detailDom = genericUtility.parseString(xmlString2);
			}
		    retStr = process(headerDom, detailDom, windowName, xtraParams);
		}
		catch (Exception e)
		{
			System.out.println("Exception :process(String xmlString, String xmlString2, String windowName, String xtraParams):" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retStr;	
	}//end of StringProcess
	
	public String process(Document headerDom, Document detailDom, String windowName, String xtraParams) throws RemoteException,ITMException
	{
		String sSel = "";
		String sIns = "";
		String lpnNo = "",printFlagStr="",currDate="",noOfLpnStr="";
		int printFlag=0,noOfLpn=0;
		
		PreparedStatement pSel = null;
		PreparedStatement pIns = null;	
		ResultSet rsSel = null;
		Connection conn = null;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		/*setting LabelType using window name*/
		
		try
		{	
			
			ConnDriver connDriver = new ConnDriver();			
			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);

			if ( windowName == null || windowName.trim().length() == 0 )
			{
				windowName = "w_lpn_no_gen";
			}
			/* selecting Key_string, Ref_ser &trns_id_col from transetup Table*/
			
			sSel = "SELECT KEY_STRING, TRAN_ID_COL,REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
			pSel = conn.prepareStatement(sSel);
			pSel.setString(1, windowName);
			rsSel = pSel.executeQuery();
			if( rsSel.next() )
			{
				keyString = rsSel.getString( "KEY_STRING" );
				tranIDCol = rsSel.getString("TRAN_ID_COL");
				refSer = rsSel.getString("REF_SER");
			}
			
			String loginCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			String siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"site_code");
			String chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			java.util.Date date = null;
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			System.out.println(genericUtility.getDBDateFormat());

			SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = simpledateformat.parse(timestamp.toString());
			timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
			currDate = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
			StringBuffer xmlValues = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>");
			xmlValues = xmlValues.append("<Header></Header>");
			xmlValues = xmlValues.append("<Detail1>");
			xmlValues.append( "<site_code>").append("<![CDATA[" + siteCode + "]]>").append("</site_code>\r\n" );
			xmlValues.append( "<tran_date>").append("<![CDATA[" + currDate + "]]>").append("</tran_date>\r\n");
			xmlValues.append( "<loginCode><![CDATA[" ).append(loginCode).append( "]]></loginCode>\r\n" );
			
			if(windowName.trim().equals("w_lpn_no_gen"))
			{
				System.out.println("printFlagStr:["+printFlagStr+"]");
				noOfLpnStr = genericUtility.getColumnValue("no_of_lpn",headerDom);
				if ( noOfLpnStr != null  )
				{
					noOfLpn = Integer.parseInt(noOfLpnStr);
				}
				else
				{
					noOfLpn=0;
				}
			}
			xmlValues = xmlValues.append( "</Detail1></Root>");
			System.out.println("@@@@@  xmlValues:["+xmlValues+"]");
			
			int updCnt[] = null;
			TransIDGenerator tg = new TransIDGenerator(xmlValues.toString(), "BASE",CommonConstants.DB_NAME);
			
			if(windowName.trim().equals("w_lpn_no_gen"))
			{
				sIns = " INSERT INTO LPN_MST (LPN_NO,PRINT_FLAG) VALUES (?,?) ";
				pIns = conn.prepareStatement(sIns);
				for( int i = 1; i <= noOfLpn ; i++ )
				{	
					lpnNo = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
					System.out.println(lpnNo);
					pIns.setString(1,lpnNo);
					pIns.setInt(2,printFlag);
					pIns.addBatch();
					pIns.clearParameters();
				}
			}
			updCnt = pIns.executeBatch();
			pIns.clearBatch();
			System.out.println("LPN NO Created :ROWS INSERTED:["+updCnt.length+"]");
			if ( updCnt.length > 0 )
			{
				conn.commit();
				ITMDBAccessLocal itmDBAccessLocal = new ITMDBAccessEJB();
				retString = itmDBAccessLocal.getErrorString("","PRCSUCCESS","");
			}
			
			
			
		}//end of try
		catch(BatchUpdateException buex)
        {
			try
			{
				conn.rollback();
				int [] updateCounts = buex.getUpdateCounts();
				for (int i = 0; i < updateCounts.length; i++)
				{
					System.err.println("  Statement " + i + ":" + updateCounts[i]);
				}
				System.err.println(" Message: " + buex.getMessage());
				System.err.println(" SQLSTATE: " + buex.getSQLState());
				System.err.println(" Error code: " + buex.getErrorCode());
				SQLException ex = buex.getNextException();
				while (ex != null)
				{ 
					System.err.println("SQL exception:");
					System.err.println(" Message: " + ex.getMessage());
					System.err.println(" SQLSTATE: " + ex.getSQLState());
					System.err.println(" Error code: " + ex.getErrorCode());
					ex = ex.getNextException();
				}
			}
			catch ( Exception e)
			{
				e.printStackTrace();
			}
			throw new ITMException(buex);
        }
		catch (Exception e)
		{
			try
			{
				if (conn != null)
				{
					conn.rollback();
				}
			}
			catch (Exception exe)
			{
				exe.printStackTrace();
			}
			e.printStackTrace();
			throw new ITMException(e);
		}
		
		finally
		{
			try
			{
				if(rsSel != null)
				{
					rsSel.close();
					rsSel = null;
				}
				if(pSel != null)
				{
					pSel.close();
					pSel = null;
				}
				if(pIns != null)
				{
					pIns.close();
					pIns = null;
				}
				if( conn != null && !conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch (Exception ex)
			{	
				ex.printStackTrace();
				throw new ITMException(ex);
			}		
		}
		return retString ;
	}//end of Process
	

}
