/**
* PURPOSE : Pre Save Logic implementation for SHIPMENT component.
* AUTHOR : Sumit Sarkar
*/

package ibase.webitm.ejb.wms;

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

import java.rmi.RemoteException;
import java.sql.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.w3c.dom.*;

import javax.ejb.*;

@javax.ejb.Stateless
public class PickIssuePrs extends ValidatorEJB implements PickIssuePrsLocal, PickIssuePrsRemote
{
	public String preSave() throws RemoteException,ITMException
	{
		return "";
	}

	public String preSave(String xmlString, String editFlag, String xtraParams, Connection conn)throws RemoteException,ITMException
	{
		String errString = "";
		System.out.println("PickIssuePrs EJB called");
		Document dom = null;
		try
		{
			System.out.println("xmlString in PickIssuePrs : preSaveRec \n"+xmlString);			
			if (xmlString != null && xmlString.trim().length() > 0)
			{
				dom = GenericUtility.getInstance().parseString(xmlString);
				errString = executepreSave( dom, editFlag, xtraParams, conn );
			}			
		}
		catch(Exception e)
		{
			System.out.println("Exception :PickIssuePrs :" + e.getMessage() + ":");
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString;
	}

	private String executepreSave( Document dom, String editFlag, String xtraParams, Connection conn ) throws RemoteException, ITMException
	{
		System.out.println("executepreSave method called");
		String sql = "";			
		String tranId = "";
		String pickOrder = "";
		/*Set ptcn = null;		
		int deleteCount = 0;
		boolean isSameWave = false;*/
		ResultSet rs = null;
		PreparedStatement pstmt = null;
		String errString = "";
		String itemCode = "",itemCodeTemp = "";
		Set itemSet = new HashSet();
		int count = 0;
		int pickOrderLine = 0;
		
		double quantity = 0.0;
		/*HashMap ptcnAndConsingnee = new HashMap();
		HashMap newPtcnAndNewConsingnee = new HashMap();*/
		
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
		try
		{			
			conn.setAutoCommit(false); 
			GenericUtility genericUtility = GenericUtility.getInstance();
			NodeList parentNodeList = null, parentNodeList1 = null;
			NodeList childList = null;
			int parentNodeListLength,parentNodeListLength1 ;
			int detLine = 0;
			Node parentNode = null,parentNode1 = null;
			String updateFlag = "",updateFlag1 = "";			
			parentNodeList = dom.getElementsByTagName("Detail2");
			parentNodeListLength = parentNodeList.getLength();
			for(int row = 0; row < parentNodeListLength; row++)
			{
				parentNode = parentNodeList.item(row);					
	        	updateFlag = getAttribValue(parentNode,"attribute", "updateFlag"); //(parentNode, "attribute", "status"));
	        	//System.out.println(" update flag ["+updateFlag+"]");
	        	if("D".equalsIgnoreCase(updateFlag))
	        	{
	        		continue;
	        	}
	        	
	        	itemCode = GenericUtility.getInstance().getColumnValueFromNode("item_code", dom.getElementsByTagName("Detail2").item(row));
	        	System.out.println(" itemCode ["+itemCode+"]");
	        	//System.out.println(" itemSet ["+itemSet+"]");
	        	
	        	if( !itemSet.contains(itemCode))
	        	{
	        		itemSet.add(itemCode);
	        		System.out.println(" itemSet ____ "+itemSet);
	        		parentNodeList1 = dom.getElementsByTagName("Detail2");
	    			parentNodeListLength1 = parentNodeList1.getLength();
	    			System.out.println(" parentNodeListLength1 ** ["+parentNodeListLength1+"]");
	    			for(int row1 = 0; row1 < parentNodeListLength1; row1++)
	    			{
	    				parentNode1 = parentNodeList1.item(row1);					
	    	        	updateFlag1 = getAttribValue(parentNode1,"attribute", "updateFlag");
	    	        	System.out.println(" updateFlag1 ********* ["+updateFlag1+"]");
	    	        	if("D".equalsIgnoreCase(updateFlag1))
	    	        	{
	    	        		continue;
	    	        	}
	    	        	
	    	        	itemCodeTemp = GenericUtility.getInstance().getColumnValueFromNode("item_code", dom.getElementsByTagName("Detail2").item(row1));
	    	        	System.out.println(" *** itemCodeTemp *** ["+itemCodeTemp+"]");
	    	        	if( itemCode.equalsIgnoreCase(itemCodeTemp) )
	    	        	{
	    	        		System.out.println(" row1 ["+row1+"]");
	    	        		pickOrder = GenericUtility.getInstance().getColumnValueFromNode("pick_order", dom.getElementsByTagName("Detail2").item(row1));
		    	        	pickOrderLine = Integer.parseInt(GenericUtility.getInstance().getColumnValueFromNode("line_no__ord", dom.getElementsByTagName("Detail2").item(row1)));
		    	        	quantity = quantity + Double.parseDouble(GenericUtility.getInstance().getColumnValueFromNode("quantity", dom.getElementsByTagName("Detail2").item(row1)));
	    	        	}
	    	        	
	    				
	    			}
	    			System.out.println(" itemCode ["+itemCode+"] pickOrder["+pickOrder+"] pickOrderLine["+pickOrderLine+"] quantity ["+quantity+"]");
	        		
	    			sql = "SELECT SUM(QUANTITY - CASE WHEN DEALLOC_QTY IS NULL THEN 0 ELSE DEALLOC_QTY END) AS QUANTITY " +
	    					" FROM PICK_ORD_DET WHERE PICK_ORDER = ? AND ITEM_CODE = ? ";
	    			
	    			pstmt = conn.prepareStatement(sql);
	    			pstmt.setString(1, pickOrder);
	    			pstmt.setString(2, itemCode);
	    			rs = pstmt.executeQuery();
	    			if( rs.next())
	    			{
	    				System.out.println(" quantity ["+rs.getDouble("QUANTITY")+"]");
	    				if( rs.getDouble("QUANTITY") != quantity)
	    				{
	    					errString = itmDBAccessEJB.getErrorString("","INVPIISQTY","","",conn);
							return errString;
	    				}
	    			}		        	
		        	rs.close(); rs = null;
		        	pstmt.close(); pstmt = null;
		        	quantity = 0;
	        	}
	        	
	        }		
			
			//Changed by sumit on 11/02/13 adding ref_ser condition
			//if( ptcn != null && ptcn.size() > 0 )
			
			System.out.println(" errString -->["+errString+"]");
			
		}
		catch (SQLException sqe)
		{
			System.out.println("The SQLException occurs in ShipmentPrs :"+sqe);
			sqe.printStackTrace();
			throw new ITMException(sqe);
		}
		catch(Exception e)
		{
			System.out.println("The Exception occurs in ShipmentPrs :"+e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch(Exception e)
			{
				System.err.println("Exception :ShipmentPrs :\n"+e.getMessage());
				e.printStackTrace();
				throw new ITMException(e);
			}
		}
		return errString;
	}
	private String checkNull( String input )	
	{
		if ( input == null )
		{
			input = "";
		}
		return input;
	}
	
	
	private String getAttribValue(Node detailNode, String nodeName, String attribStr)
	{
		String attribValue = "";
		try
		{
			String domStr = GenericUtility.getInstance().serializeDom(detailNode);
			Document dom = GenericUtility.getInstance().parseString(domStr);
			if( dom != null /*&& dom.getAttributes() != null*/)
			{
				Node attributeNode = dom.getElementsByTagName( nodeName ).item(0);
				attribValue = getAttribValue(attributeNode, attribStr);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
	private String getAttribValue(Node detailNode, String attribStr)
	{
		String attribValue = "";
		try
		{
			if( detailNode != null && detailNode.getAttributes() != null)
			{
				Node attribNode = detailNode.getAttributes().getNamedItem( attribStr );
				if( attribNode != null )
				{
					attribValue = checkNull( attribNode.getNodeValue() );
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
	
	
}
