/**
* 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.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.sql.PreparedStatement;
import ibase.webitm.utility.TransIDGenerator;
import ibase.utility.CommonConstants;

import java.util.ArrayList;
import java.util.TreeMap;
import ibase.webitm.reports.utility.JasperReportGenerator;
import ibase.webitm.reports.utility.XSDParser;
import java.util.Random;

@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 = "";
		String printer = "";
	    String PalletLabel = "";
		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'
			ArrayList al = new ArrayList();
			
			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();
					
					al.add(palletNo);
				}
				
			}
			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();
				
				//Changed By Sankara on 19/11/2012 to Call Report [Start]
				 printer = checkNull(genericUtility.getColumnValue("printer_name",headerDom));
				 PalletLabel = checkNull(genericUtility.getColumnValue("pallet_label",headerDom));
				 System.out.println(" pallete -["+palletNo+"]");
				 if("Y".equalsIgnoreCase(PalletLabel) && al.size() > 0)
				 {
					 System.out.println(" array first ->["+al.get(0).toString()+"] last array ->["+al.get(numPallet-1).toString()+"]");
					String reportString = generateReport(printer,"A", al.get(0).toString() ,al.get(numPallet-1).toString(), conn);
					System.out.println("***reportString***************"+reportString);
				 }
				//Changed By Sankara on 19/11/2012 to Call Report [End]
				 
				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
	//Changed by Sankara on 19/11/2012 to Call Report [Start]
	private String generateReport(String printer, String status, String palletNoFirst, String palletNoLast, Connection conn) throws ITMException
    {
    	String errString ="";
        String reportObjName = "";    	
    	PreparedStatement pstmt = null;
    	ResultSet rs = null;
    	DistCommon discommon = new DistCommon();    	
    	String chgUser = "";
    	
    	try
    	{
    		reportObjName = checkNull(discommon.getDisparams("999999","CARTON_GEN_OBJNAME",conn));
		    System.out.println("Printer *->["+printer.trim()+"]  report_obj_name ["+reportObjName+"] ");
			System.out.println("inside report  generation :: and pallet no 1 ["+palletNoFirst+"] pallet last ->["+palletNoLast+"]");
		    ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();     
					String xsdString ="<Arguments>" +
								"<Argument id=\"pallet_no_fr\" name=\"pallet_no_fr\">" +
								"<argType>java.lang.String</argType>" +
								//"<value>"+ptcnList.get(i)+"</value>" +
								"<value>"+palletNoFirst+"</value>" +
								"</Argument>" +
								"<Argument id=\"pallet_no_to\" name=\"pallet_no_to\">" +
								"<argType>java.lang.String</argType>" +
								//"<value>"+ptcnList.get(i)+"</value>" +
								"<value>"+palletNoLast+"</value>" +
								"</Argument>" +
								"<Argument id=\"as_status\" name=\"as_status\">" +
								"<argType>java.lang.String</argType>" +
								//"<value>"+ptcnList.get(i)+"</value>" +
								"<value>"+status+"</value>" +
								"</Argument>" +
								"<Argument id=\"x_path\" name=\"x_path\">" +
								"<argType>java.lang.String</argType>" +
								"<value>/DocumentRoot/pallet_no</value>" +
								"</Argument>" +
								"<Argument id=\"design_source\" name=\"design_source\">" +
								"<argType>java.lang.String</argType>" +
								"<value>pallet_no.jrxml</value>" +
								"</Argument>" +
								"<Argument id=\"data_source\" name=\"data_source\">" +
								"<argType>java.lang.String</argType>" +
								"<value>SQL</value>" +
								"</Argument>" +
								"<Argument id=\"bind_type\" name=\"bind_type\">" +
								"<argType>java.lang.Integer</argType>" +
								"<value>0</value>" +
								"</Argument>" +
								"<Argument id=\"report_type\" name=\"report_type\">" +
								"<argType>java.lang.String</argType>" +
								"<value>JASPER</value>" +
								"</Argument>" +
								"<Argument id=\"report_save_type\" name=\"report_save_type\">" +
								"<argType>java.lang.String</argType>" +								
								"<value>NATIVE</value>" +									
								"</Argument>" +
								"</Arguments>";
					System.out.println(" XSD parser **->["+xsdString+"]");
					errString = jrGenerator.printReport(reportObjName, xsdString, chgUser, printer.trim(), 1, conn);
				}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    		throw new ITMException(e);
    	}
    	finally
    	{
    		try 
    		{
    			if( pstmt != null)
    			{
					pstmt.close();
					pstmt = null;
    			}
    			if( rs != null)
    			{
    				rs.close();
    				rs = null;
    			}
				
			} 
    		catch (Exception e2) 
			{
				throw new ITMException(e2);
			}
    	}
    	return errString;
    }
	//Changed by Sankara on 19/11/2012 to Call Report [End]
	private String checkNull( String input )
	{
		if( input == null )
		{
			input = "";
		}
		else
		{
			input = input.trim();
		}
		return input;
	}
}