/**
* PURPOSE : EJB for Carton no Process
* AUTHOR : Changed By Chaitali On 25/11/2011 
*/

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 ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;

@javax.ejb.Stateless
public class CartonNoGenPrc extends ProcessEJB implements CartonNoGenPrcLocal,CartonNoGenPrcRemote
{
	String siteCode = "";
	String noOfCarton = "";
	String noOfPallet = "";
	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 cartonID = "";
		String palletNo = "";
		int numCarton = 0;
		int numPallet = 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_carton_no_gen";
			}
			/*selectin 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 chgUser = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			String chgTerm = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"chgTerm");
			
			StringBuffer xmlValues = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>");
			xmlValues = xmlValues.append("<Header></Header>");
			xmlValues = xmlValues.append("<Detail1>");
			//commented by Mahesh Patidar on 05/06/12
			//xmlValues = xmlValues.append("<carton_no></carton_no>");
			//ended By Mahesh Patidar
			//Added By Mahesh Patidar on 05/06/12
			if(windowName.trim().equals("w_palletprc"))
			{

				noOfPallet = checkNull(genericUtility.getColumnValue("no_of_pallet",headerDom));
				if ( noOfPallet.length() > 0 )
				{
					numPallet = Integer.parseInt(noOfPallet);
				}
				xmlValues = xmlValues.append("<pallet_no></pallet_no>");
			}
			else
			{
				noOfCarton = checkNull(genericUtility.getColumnValue("no_of_cartons",headerDom));
				if ( noOfCarton.length() > 0 )
				{
					numCarton = Integer.parseInt(noOfCarton);
				}
				xmlValues = xmlValues.append("<carton_no></carton_no>");
			}
			//ended By Mahesh Patidar
			xmlValues = xmlValues.append( "</Detail1></Root>");
			
			Timestamp currDate = new Timestamp(System.currentTimeMillis());
			int updCnt[] = null;
			TransIDGenerator tg = new TransIDGenerator(xmlValues.toString(), "BASE",CommonConstants.DB_NAME);
			//CHANGED BY MAHESH PATIDAR ON 05/06/12 FOR REQUEST 'WM2CSUN001'
		/*
			String sIns = " INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM) VALUES (?,?,?,?,?) ";
			pIns = conn.prepareStatement(sIns);
			for( int i = 1; i <= numCarton ; i++ )
			{
				cartonID = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
				System.out.println(cartonID);
				pIns.setString(1,cartonID);
				pIns.setString(2,"A");
				pIns.setTimestamp(3,currDate);
				pIns.setString(4,chgUser);
				pIns.setString(5,chgTerm);
				pIns.addBatch();
				pIns.clearParameters();
			}//end of for 
		*/
			//END COMMENT BY MAHESH PATIDAR
			
			//ADDED BY MAHESH PATIDAR ON 05/06/12 FOR REQUEST 'WM2CSUN001'
			if(windowName.trim().equals("w_palletprc"))
			{
				sIns = " INSERT INTO PALLET_NO (PALLET_NO,STATUS) VALUES (?,'A') ";  //change by Kunal Mandhre on 28/07/12 insert status as per S Manoharan instruction 
				pIns = conn.prepareStatement(sIns);
				for( int i = 1; i <= numPallet ; i++ )
				{
					palletNo = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
					System.out.println(palletNo);
					pIns.setString(1,palletNo);
					pIns.addBatch();
					pIns.clearParameters();
				}
			}
			else
			{
				sIns = " INSERT INTO CARTON_MASTER (CARTON_NO, STATUS, CHG_DATE, CHG_USER, CHG_TERM) VALUES (?,?,?,?,?) ";
				pIns = conn.prepareStatement(sIns);
				for( int i = 1; i <= numCarton ; i++ )
				{
					cartonID = tg.generateTranSeqID(refSer, tranIDCol, keyString, conn);
					System.out.println(cartonID);
					pIns.setString(1,cartonID);
					pIns.setString(2,"A");
					pIns.setTimestamp(3,currDate);
					pIns.setString(4,chgUser);
					pIns.setString(5,chgTerm);
					pIns.addBatch();
					pIns.clearParameters();
				}
			}
			//ENDED BY MAHESH PATIDAR
			updCnt = pIns.executeBatch();
			pIns.clearBatch();
			System.out.println(":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 DOCProcess
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
}