/*******************************************    
	Title : CheckSheetPostSave
    Date  : 16/06/12
    Author: Kunal Mandhre

 ********************************************************/
package ibase.webitm.ejb.wms;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import java.rmi.RemoteException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.w3c.dom.*;

@javax.ejb.Stateless
public class CheckSheetPos extends ValidatorEJB implements CheckSheetPosLocal, CheckSheetPosRemote
{
	public String postSave()throws RemoteException,ITMException
	{
		return "";
	}
	public String postSave(String domString, String tranId,String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{
		String errString = "";
		String sql = "";
		String sqlRes = "";
		//String palletNo = "";
		String shipmentId = "";
		String refId = "";
		String ptcn = "";
		boolean isError = false;
		String forcedFlag = "false";
		Document dom = null;
		PreparedStatement pstmt = null;
		PreparedStatement pstmtRes = null;
		ResultSet rs = null;
		ResultSet rsRes = null;
		ConsolidatToDoc contoDoc = new ConsolidatToDoc();
		ShipmentConf shipConf = new ShipmentConf();
		int noOfParent= 0 ,noOfChilds = 0;
		String columnValue = "";
		String palletNo = "", palletNoDB = "",cartonNo = "";

		String sql1 = "";
		String sql2 = "";
		String waveId = "";
		String pickType = "";
		String orderType = "";
		String replOrder = "";
		String pickOrder = "";
		//Changed by sumit on 10/11/12 create variable  
		String printer = "";
		PreparedStatement pstmt1 = null;
		PreparedStatement pstmt2 = null;
		ResultSet rs1 = null ;
		ResultSet rs2 = null ;
		ArrayList allPallets = new ArrayList<String>();		
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		int noOfPalletScanned=0;

		try
		{
			conn.setAutoCommit(false);
			GenericUtility genericUtility = GenericUtility.getInstance();
			dom = genericUtility.parseString(domString);
			System.out.println("Dom String ="+domString);
			shipmentId = genericUtility.getColumnValue("shipment_id", dom, "1", "1");
			//Changed by sumit on 10/11/12 getting printer from header
			printer = checkNull(genericUtility.getColumnValue("printer_name", dom, "1", "1"));
			System.out.println(" printer ->["+printer+"]");
			//palletNo = genericUtility.getColumnValueFromNode("palletNo", dom.getElementsByTagName("Detail2").item(0));
			if(shipmentId != null && shipmentId.trim().length() > 0)
			{
				// sql = "select ref_id from ship_docs where  shipment_id = ? ";
				// pstmt = conn.prepareStatement( sql );
				// pstmt.setString( 1, shipmentId);
				// rs = pstmt.executeQuery();
				// while ( rs.next() )
				// {

					// refId = rs.getString("ref_id");
					// System.out.println("REF ID = "+refId);
					// //start  added by Kunal on 21/08/12 for check no of pallet scanned 
					// sqlRes = "select wave_id ,ptcn from wave_task_det where  ref_id = ? and ref_ser = 'S-DSP'";
					// pstmtRes = conn.prepareStatement( sqlRes );
					// pstmtRes.setString( 1, refId);
					// rsRes = pstmtRes.executeQuery();
					// while ( rsRes.next() )
					// {

						// waveId = rsRes.getString("wave_id");
						// ptcn = rsRes.getString("ptcn");
						// System.out.println("wave id = "+waveId);								
						// //for pick iss
						//sql1 = "select pick_order,pick_type from pick_ord_hdr p,wave_task_det w where p.wave_id = w.wave_id and w.ptcn = ? and w.ref_id = p.pick_order and p.wave_id = ?";
						//Changes by sumit on 04/10/12 getting desp_id value to confirmed 
						/*sql = "SELECT DISTINCT S.PALLET_NO AS PLTNO FROM DESPATCHDET S WHERE "
							+" S.DESP_ID IN (SELECT REF_ID FROM SHIP_DOCS WHERE  SHIPMENT_ID = ?)"
							+" ORDER BY S.PALLET_NO ";*/
						sql = "SELECT DISTINCT S.PALLET_NO AS PLTNO, DESP_ID FROM DESPATCHDET S WHERE "
								+" S.DESP_ID IN (SELECT REF_ID FROM SHIP_DOCS WHERE  SHIPMENT_ID = ? AND DESP_CONFIRMED = ? AND REF_SER = ? )"							
								+" ORDER BY S.PALLET_NO ";

						pstmt1 = conn.prepareStatement( sql );
						pstmt1.setString( 1, shipmentId);
						pstmt1.setString(2, "N");
						pstmt1.setString(3, "S-DSP");
						//pstmt1.setString( 2, waveId);
						rs1 = pstmt1.executeQuery();
						while ( rs1.next() )
						{
							//pickOrder = rs1.getString("pick_order");
							//pickType = rs1.getString("pick_type") ;							

							//sql2 = "select pallet_no from pick_iss_hdr where pick_order = ?";
							//pstmt2 = conn.prepareStatement( sql2 );
							//pstmt2.setString( 1, pickOrder);
							//rs2 = pstmt2.executeQuery();
							//while ( rs2.next() )
							//{
								palletNo = rs1.getString("PLTNO");
								allPallets.add(palletNo);								
							//}
							//rs2.close(); rs2 = null;
							//pstmt2.close(); pstmt2 = null;

						}
						rs1.close(); rs1 = null;
						pstmt1.close(); pstmt1 = null;				
						
						//for repl iss
						sql1 = "select repl_order,order_type from repl_ord_hdr r,wave_task_det w where r.wave_id = w.wave_id and w.ptcn = ? and w.ref_id = r.repl_order and r.wave_id = ? ";
						pstmt1 = conn.prepareStatement( sql1 );
						pstmt1.setString( 1, ptcn);
						pstmt1.setString( 2, waveId);
						rs1 = pstmt1.executeQuery();
						while ( rs1.next() )
						{
							replOrder = rs1.getString("repl_order");
							orderType = rs1.getString("order_type") ;									


							sql2 = "select carton_no from repl_iss_hdr where repl_order = ?";
							pstmt2 = conn.prepareStatement( sql2 );
							pstmt2.setString( 1, replOrder);
							rs2 = pstmt2.executeQuery();
							while ( rs2.next() )
							{

								if("D".equalsIgnoreCase(orderType) || "L".equalsIgnoreCase(orderType))
								{
									cartonNo = rs2.getString("carton_no");
									allPallets.add(cartonNo);
								}
							}
							rs2.close(); rs2 = null;
							pstmt2.close(); pstmt2 = null;
						 }
						 rs1.close(); rs1 = null;
						 pstmt1.close(); pstmt1 = null;

					// }
					// rsRes.close(); rsRes = null;
					// pstmtRes.close(); pstmtRes = null;
				//}
				//rs.close(); rs = null;
				//pstmt.close(); pstmt = null;

				System.out.println("All pallets="+allPallets);

				NodeList parentList = dom.getElementsByTagName( "Detail2");
				noOfParent = parentList.getLength();
				
				pstmt = conn.prepareStatement(sql);
				for ( int ctr1 = 0; ctr1 < noOfParent; ctr1++ )  //Loop for each node of current detail
				{
						palletNo = genericUtility.getColumnValueFromNode( "pallet_no", parentList.item(ctr1) );
						System.out.println("palletno = "+palletNo);
						if(allPallets.contains(palletNo))
						{
							System.out.println("pallet scanned");
							noOfPalletScanned++;
							
						}						
						
				}
				pstmt.close();
				pstmt = null;
				System.out.println("No of pallet scanned ="+noOfPalletScanned);
				System.out.println("Total No of pallet ="+allPallets.size());
				if(allPallets.size() == noOfPalletScanned)
				{					
						//Changed by sumit on 05/10/12 commented as a wrong method.
						errString = shipConf.confirm(shipmentId, xtraParams, forcedFlag, conn);
						System.out.println("Error String  = "+errString);
						System.out.println("SHIP CONF CALLED ");
						errString = shipConf.confirm(shipmentId, xtraParams, forcedFlag);						
						System.out.println("Error String  = "+errString);
						
						if( errString.contains("VTCONFIRM") && printer.trim().length() > 0)
						{
							errString = generateBOLReport(shipmentId, printer, conn, xtraParams);
						}
						else
						{
							isError = true;
							return errString;
						}

				}
				else
				{
					isError = true;
					errString = itmDBAccessEJB.getErrorString("","VTPLTSCN","","",conn);
					return errString;
				}
				//end  by Kunal on 21/08/12

				/*sql = "select ref_id from ship_docs where  shipment_id = ? "; //change done by Kunal on 02/08/12 as per S Manoharan instruction  
				pstmt = conn.prepareStatement( sql );
				pstmt.setString( 1, shipmentId);
				rs = pstmt.executeQuery();
				while ( rs.next() )
				{
					refId = rs.getString("ref_id");
					sqlRes = "select ptcn from wave_task_det where  ref_id = ? and ref_ser = 'S-DSP'";
					pstmtRes = conn.prepareStatement( sqlRes );
					pstmtRes.setString( 1, refId);
					rsRes = pstmtRes.executeQuery();
					while ( rsRes.next() )
					{
						ptcn = rsRes.getString("ptcn");
						errString =  contoDoc.process(ptcn, conn);
						System.out.println("error String ="+errString);
						if ( errString != null && errString.trim().length() > 0 )
						{
							isError = true;
							return errString;
						}
						conn.commit();
						shipConf.confirm(shipmentId, xtraParams, forcedFlag, conn);
						System.out.println("SHIP CONF CALLED");
						shipConf.confirm(shipmentId, xtraParams, forcedFlag);



					}
					rsRes.close(); rsRes = null;
					pstmtRes.close(); pstmtRes = null;
				}
				rs.close(); rs = null;
				pstmt.close(); pstmt = null;
				 */

			}
		}
		catch(Exception e)
		{
			isError = true;
			System.out.println("Exception "+e.getMessage());
			e.printStackTrace();
			try
			{
				conn.rollback();
			}
			catch(Exception e1)
			{
				e1.printStackTrace();
				throw new ITMException(e1);
			}
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( !isError )
				{
					conn.commit();// For committing the transaction update
				}
				else 
				{
					conn.rollback();
				}
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :CheckSheetPos :\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}
	
	//Changed by sumit on 10/11/12 on  
	private String generateBOLReport(String shipmnetId, String printer, Connection conn, String xtraParams) throws ITMException
	{
		String sql = "";
		String reportObjName = "";
		//String refId = "";
		String errString = "";
		String loginCode = "";
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		try
		{
			GenericUtility genericUtility = GenericUtility.getInstance();
			System.out.println(" calling BOL report -------------------");
			loginCode = checkNull(genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" ));
			DistCommon discommon = new DistCommon();	
			reportObjName = discommon.getDisparams("999999","LOADING_REP_OBJNAME",conn);
			/*sql = "SELECT REF_ID, REF_SER FROM SHIP_DOCS WHERE SHIPMENT_ID = ? AND DESP_CONFIRMED = 'Y'";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, shipmnetId);						
			rs = pstmt.executeQuery();*/					
			ibase.webitm.reports.utility.JasperReportGenerator jrGenerator = new ibase.webitm.reports.utility.JasperReportGenerator();
			String xsdString ="<Arguments>" +
						"<Argument id=\"DESP_ID_FIRST\" name=\"DESP_ID_FIRST\">" +
						"<argType>java.lang.String</argType>" +						
						"<value>"+shipmnetId+"</value>" +
						"</Argument>" +
						"<Argument id=\"DESP_ID_LAST\" name=\"DESP_ID_LAST\">" +
						"<argType>java.lang.String</argType>" +						
						"<value>"+shipmnetId+"</value>" +
						"</Argument>" +
						"<Argument id=\"x_path\" name=\"x_path\">" +
						"<argType>java.lang.String</argType>" +
						"<value>/DocumentRoot/bill_of_lading</value>" +
						"</Argument>" +
						"<Argument id=\"design_source\" name=\"design_source\">" +
						"<argType>java.lang.String</argType>" +
						"<value>bill_of_lading.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, loginCode, printer.trim(), 1, conn);
			
		}
		catch(Exception e)
		{
			System.err.println("Exception :CheckSheetPos :\n"+e.getMessage());
			e.printStackTrace();
			throw new ITMException(e);
		}
		return null;
	}
	private String checkNull(String str)
	{
		if( str == null)
		{
			str = "";
		}
		return str;
	}
}

