
/**
* PURPOSE : post save for Desp Pack Det
* AUTHOR : Changed By Sumit On 22/09/2011 [WM1FSUN004] 
*/ 
package ibase.webitm.ejb.wms;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql. PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

import org.w3c.dom.*;

import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class DespPackPostEJB extends ValidatorEJB implements DespPackPostEJBLocal, DespPackPostEJBRemote{	
	
	/**
	* The method defined with no parameter and returns nothing
	*/
	public String postSave()throws RemoteException,ITMException
	{
		return "";
	}
	
	/**
	 * The public method is used for post save of required fields which return called overloaded method
	 * Returns post save string if exist otherwise returns null in XML format
	 * @param winName contain window name
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param conn contains the connection 
	 * @param domString contains domString
	*/ 
	public String postSave( String domString, String editFlag, String xtraParams, Connection conn ) throws RemoteException,ITMException
	{  
		String objName = "";
		String sql = "", sql1 = "", sql2 = "";
		PreparedStatement pstmt = null , pstmt2 = null, pstmt1 = null;
		Document dom = null;
		boolean isError = false;
		boolean isLocalConn = false;
		ResultSet rs = null, rs1 = null; 
		String childNodeName = "";
		//String confirmFlag = null;
		
		NodeList parentNodeList = null, childNodeList  = null;
		Node parentNode = null, childNode = null;
	    int parentNodeListLength = 0;
	    
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		String errorMsg = "", outerCartonNo = "", expLev = "0";
		String tranId = "",saleOrder = "",itemCode = "",locCode = "",lotSl = "",locCodeTo = "", siteCode = "", lotNo ="";
		String unit = "",unitDimn = "", packCode = "", mfrPartNo = "", custItemRef = "", dimension = "", siteCodeMFG = "";
		int lineNo = 0,lineNoSord =0,quantity = 0, noArt = 0;
		int i = 0 , discount = 0, grossWeight = 0, tareWeight = 0, netWeight =0;
		Float rate = 0.0f, discAMT = 0.0f;
		
		Timestamp  mfgDate = null, expDate = null, ratestDate =null;
		try
		{
			conn.setAutoCommit( false );
			System.out.println("All dom Str["+domString+"]");
			dom = genericUtility.parseString(domString);
			objName  = getObjNameFromDom( dom, "objName");
			System.out.println("objName["+objName+"]");
			
			String despId  = checkNull( genericUtility.getColumnValue("desp_id", dom,  "1", "") );
			System.out.println("despId ["+despId+"]");
			outerCartonNo  = checkNull( genericUtility.getColumnValue("outer_carton_no", dom,  "1", "") );
			System.out.println("************outerCartonNo ["+outerCartonNo+"]");
			
			//TAKE DETAIL2 FROM THE DOM
			
			parentNodeList = dom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength(); 
			
			for(int row = 0; row < parentNodeList.getLength(); row++)
			{
				parentNode = parentNodeList.item(row);
				childNodeList = parentNode.getChildNodes();
				
				outerCartonNo = "";
				
				System.out.println("************* first For loop *************["+parentNode.getNodeName()+"]");
				for(int col = 0; col < childNodeList.getLength(); col++)
				{
					childNode = childNodeList.item(col);
					
					if(childNode.getNodeType() == childNode.ELEMENT_NODE)
					{
						childNodeName = childNode.getNodeName();
						System.out.println("childNodeNamechildNodeName ** ["+childNodeName+"]");
						
						if("outer_carton_no".equalsIgnoreCase(childNodeName))
						{
							outerCartonNo = childNode.getFirstChild().getNodeValue();
							outerCartonNo = outerCartonNo != null ? outerCartonNo : "";
							System.out.println("*******outerCartonNo-->"+outerCartonNo);							
						}
					}
				}			
				//GET OUTER COTON NO THEN SELECT THE DATA REQUIRED
				//INSERT
				sql = 	"SELECT P.TRAN_ID, P.LINE_NO, P.SALE_ORDER, P.LINE_NO__SORD," +
						"P.SITE_CODE, P.ITEM_CODE, P.LOC_CODE, P.LOT_NO, P.LOT_SL," +
						"P.QUANTITY, P.NO_ART, I.UNIT, I.UNIT__DIMN, I.PACK_CODE, I.MFR_PART_NO," +
						"SO.DISCOUNT, SO.CUST_ITEM__REF FROM PACK_DET P, WAVE_TASK_DET W, " +
						"DESPATCH D , ITEM I, SORDDET SO WHERE D.DESP_ID = ? " +
						"AND P.OUTER_CARTON_NO = ? " +
						"AND D.WAVE_ID = W.WAVE_ID " +
						"AND P.TRAN_ID = W.REF_ID " +
						"AND P.ITEM_CODE = I.ITEM_CODE " +
						"AND P.SALE_ORDER = SO.SALE_ORDER " +
						"AND P.LINE_NO = SO.LINE_NO "; 				
				
				System.out.println("SQL ["+sql+"]");
				pstmt = conn.prepareStatement(sql);
				despId = setChar(despId);			
				pstmt.setString(1, despId);
				pstmt.setString(2, outerCartonNo);
				rs = pstmt.executeQuery();				
				System.out.println("Query Executed***********");			
				
				while (rs.next())
				{
					System.out.println("inside while loop");
					tranId = rs.getString("TRAN_ID");
					lineNo = rs.getInt("LINE_NO");
					saleOrder = rs.getString("SALE_ORDER");					
					lineNoSord = rs.getInt("LINE_NO__SORD");
					siteCode = rs.getString("SITE_CODE");					
					itemCode = rs.getString("ITEM_CODE");					
					locCode = rs.getString("LOC_CODE");					
					lotNo = rs.getString("LOT_NO");					
					lotSl = rs.getString("LOT_SL");					
					quantity = rs.getInt("QUANTITY");					
					noArt = rs.getInt("NO_ART");
					unit = rs.getString("UNIT");
					unitDimn = rs.getString("UNIT__DIMN");
					packCode = rs.getString("PACK_CODE");
					mfrPartNo = rs.getString("MFR_PART_NO");
					discount = rs.getInt("DISCOUNT");
					custItemRef = rs.getString("CUST_ITEM__REF");
					
					System.out.println("*****itemCode "+itemCode);
					System.out.println("*****siteCode "+siteCode);
					System.out.println("*****locCode "+locCode);
					System.out.println("*****lotNo "+lotNo);
					System.out.println("*****lotSl "+lotSl);
					
					sql1 = "SELECT EXP_DATE, MFG_DATE, SITE_CODE__MFG, RATE, NET_WEIGHT, GROSS_WEIGHT, " +
							"TARE_WEIGHT, DIMENSION, RETEST_DATE FROM STOCK WHERE ITEM_CODE = ? " +
							"AND SITE_CODE = ? AND LOC_CODE = ? AND LOT_NO = ? AND LOT_SL = ? ";
					
					System.out.println("SQL ["+sql1+"]");
					pstmt1 = conn.prepareStatement(sql1);	
					pstmt1.setString(1, itemCode);
					pstmt1.setString(2, siteCode);
					pstmt1.setString(3, locCode);
					pstmt1.setString(4, lotNo);
					pstmt1.setString(5, lotSl);
					rs1 = pstmt1.executeQuery();
					System.out.println("************ stock select query executed *****");
					if(rs1.next())
					{
						expDate = rs1.getTimestamp("EXP_DATE");
						mfgDate = rs1.getTimestamp("MFG_DATE");
						siteCodeMFG = rs1.getString("SITE_CODE__MFG");
						rate = rs1.getFloat("RATE");
						netWeight = rs1.getInt("NET_WEIGHT");
						grossWeight = rs1.getInt("GROSS_WEIGHT");
						tareWeight = rs1.getInt("TARE_WEIGHT");		
						dimension = rs1.getString("DIMENSION");
						ratestDate = rs1.getTimestamp("RETEST_DATE");						
					}
					System.out.println("Stock query Executed***********");
					 if(rs1 !=null)
					 {
						 rs1.close();
						 rs1 = null;
					 }
					 if(pstmt1 !=null)
					 {
						 pstmt1.close();
						 pstmt1 = null;
					 }
					 
					 netWeight = netWeight*noArt;
					 System.out.println("--netWeight-->"+netWeight);
					 grossWeight = grossWeight*noArt;
					 System.out.println("--grossWeight-->"+grossWeight);
					 tareWeight =tareWeight*noArt;
					 System.out.println("--tareWeight-->"+tareWeight);
					 
					System.out.println("Query Executed***********");
	
					sql2 = 	"INSERT INTO DESPATCHDET( DESP_ID, LINE_NO, SORD_NO, LINE_NO__SORD, EXP_LEV, ITEM_CODE__ORD," + 
							"ITEM_CODE, LOT_NO, LOT_SL, QUANTITY__ORD, QUANTITY, LOC_CODE, STATUS, CONV__QTY_STDUOM, UNIT__STD," +
							"UNIT, QUANTITY__STDUOM, QUANTITY_REAL, RATE__STDUOM, NO_ART, SITE_CODE, GROSS_WEIGHT, TARE_WEIGHT," +
							"NETT_WEIGHT, MFG_DATE, EXP_DATE, SITE_CODE__MFG, RATE__CLG, DIMENSION,TAX_AMT, DISC_AMT,CONF_DIFF_AMT," +
							"RATE__STD, COST_RATE, LINE_TYPE,CONV__RTUOM_STDUOM,UNIT__DIM, PACK_CODE,CUST_ITEM__REF, ITEM_CODE__REF,"+
							"RETEST_DATE, PART_NO)" +
							"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
					
					System.out.println(" SQL ******** ["+sql2+"]");
					i++;
					//DESP_ID, LINE_NO, SORD_NO, LINE_NO__SORD, EXP_LEV, ITEM_CODE__ORD," +
					pstmt2 = conn.prepareStatement(sql2);				
					pstmt2.setString(1,despId.trim());
					pstmt2.setInt(2,i);
					pstmt2.setString(3,saleOrder.trim());
					pstmt2.setInt(4,i);
					pstmt2.setString(5,expLev);
					pstmt2.setString(6,itemCode.trim());
					
					//ITEM_CODE, LOT_NO, LOT_SL, QUANTITY__ORD, QUANTITY, LOC_CODE, STATUS, CONV__QTY_STDUOM, UNIT__STD," + //15
					pstmt2.setString(7,itemCode.trim());
					pstmt2.setString(8,lotNo.trim());
					pstmt2.setString(9,lotSl.trim());
					pstmt2.setInt(10,quantity);
					pstmt2.setInt(11,quantity);
					pstmt2.setString(12,locCode.trim());
					pstmt2.setString(13,"O");
					pstmt2.setInt(14,1);
					pstmt2.setString(15,unit);
					
					//UNIT, QUANTITY__STDUOM, QUANTITY_REAL, RATE__STDUOM, NO_ART, SITE_CODE, GROSS_WEIGHT, TARE_WEIGHT," +  //23
					pstmt2.setString(16,unit);
					pstmt2.setInt(17,quantity);
					pstmt2.setInt(18,quantity);
					pstmt2.setFloat(19,rate); // rate from stock
					pstmt2.setInt(20,noArt); // from stock quantity/qty-per-art
					pstmt2.setString(21,siteCode.trim());
					pstmt2.setFloat(22,grossWeight); // Gross wt. per art * (from stock quantity/qty-per-art)
					pstmt2.setFloat(23,tareWeight); // tare wt. per art * (from stock quantity/qty-per-art)
					
					//NETT_WEIGHT, MFG_DATE, EXP_DATE, SITE_CODE__MFG, RATE__CLG, DIMENSION,TAX_AMT, DISC_AMT,CONF_DIFF_AMT
					pstmt2.setFloat(24,netWeight); // nett wt. per art * (from stock quantity/qty-per-art)
					pstmt2.setTimestamp(25,mfgDate);
					pstmt2.setTimestamp(26,expDate);
					pstmt2.setString(27,siteCodeMFG);
					pstmt2.setFloat(28,rate);
					pstmt2.setString(29,dimension);					
					pstmt2.setInt(30,0);
					discAMT  = quantity * rate * discount/100;
					pstmt2.setFloat(31,discAMT);// quantity * rate * sorddet discount/100 
					pstmt2.setFloat(32,0);
					
					//RATE__STD, COST_RATE, LINE_TYPE,CONV__RTUOM_STDUOM,UNIT__DIM, PACK_CODE,CUST_ITEM__REF, ITEM_CODE__REF
					pstmt2.setInt(33,0);
					pstmt2.setFloat(34,rate);
					pstmt2.setString(35,"I");
					pstmt2.setInt(36,1);
					pstmt2.setString(37,unitDimn);
					pstmt2.setString(38,packCode);
					pstmt2.setString(39,custItemRef);
					pstmt2.setInt(40,0);
					
					//RETEST_DATE, PART_NO
					pstmt2.setTimestamp(41,ratestDate); // From stock
					pstmt2.setString(42,mfrPartNo);// item Master					
					
					pstmt2.executeUpdate();
					System.out.println("************execution of despatchdet*********");
					pstmt2.clearParameters();
					System.out.println("insertion executed successfully ***********");
				}
			}
			
			if(pstmt2 !=null)
			{
				pstmt2.close();
				pstmt2 = null;
			}
			if(rs!=null)
			{
				rs.close();
				rs.close();
			}
			if(pstmt!=null)pstmt.close();
			
		}
		catch(Exception e)
		{
			System.out.println("Exception: DespPackPostEJB: postSave(Document dom): " + e.getMessage() + ":");
			e.printStackTrace();
			errorMsg = genericUtility.createErrorString(e);
			System.out.println("**************"+errorMsg);
			isError = true;
		}
		finally
		{
			try
			{
				System.out.println("isError ["+isError+"]");
				System.out.println("isLocalConn ["+isLocalConn+"]");
				
				if( isError )
				{
					conn.rollback();
				}
				if(pstmt2 !=null)
				{
					pstmt2.close();
					pstmt2 = null;
				}
				if(pstmt1 !=null)
				{
					if(rs1 != null)
					{
						rs1.close();
						rs1 = null;
					}
					pstmt1.close();
					pstmt1 = null;
					
				}			
				
				if( pstmt != null )
				{
					if(rs != null)
					{
						rs.close();
						rs = null;
					}
					pstmt.close();
					pstmt = null;
				}
					
			}
			catch (Exception e)
			{
				e.printStackTrace();
				errorMsg = genericUtility.createErrorString(e);
			}
		}
		
	 return errorMsg;
	}// end of post save method
	
	private String checkNull(String input)
	{
		if (input==null)
		{
			input="";
		}
		return input;
	}
	private static String setChar(String despId)
	{
		despId = despId+ "          ";
	    return despId.substring(0, 10);
	 }
	private String getObjNameFromDom( Document dom, String attribute ) throws RemoteException,ITMException
	{
		String objName = "";
		try
		{
			NodeList detailList = null;
			Node currDetail = null;			
			int	detailListLength = 0;

			detailList = dom.getElementsByTagName("Detail2");
			detailListLength = detailList.getLength();
			for (int ctr = 0;ctr < detailListLength;ctr++)
			{
				currDetail = detailList.item(ctr);
				objName = currDetail.getAttributes().getNamedItem(attribute).getNodeValue();
						
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return objName;
	}

}
