

package ibase.webitm.ejb.wms;

import java.io.*;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.util.*;
import java.util.Date;

import javax.ejb.*;
import javax.naming.InitialContext;
import javax.xml.parsers.*;
import org.w3c.dom.*;

import ibase.ejb.*;
import ibase.system.config.*;
import ibase.utility.BaseLogger;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
import ibase.webitm.ejb.ITMDBAccessEJB;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import org.xml.sax.InputSource;
import java.net.InetAddress;

@javax.ejb.Stateless
public class PickIssueEJB extends ValidatorEJB implements PickIssueEJBRemote,PickIssueEJBLocal  
{
	// Validation Code. Start	
	/**
	 * The method is defined without any parameter and returns blank string
	 */
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	/**
	 * The public method is used for converting the current form data into a document(DOM)
	 * The currDom is then given as argument to the overloaded function wfValData to perform validation
	 * Returns validation string if exists else returns null in XML format
	 * @param currFrmXmlStr contains the current form data in XML format
	 * @param hdrFrmXmlStr contains all the header information in the XML format
	 * @param allFrmXmlStr contains the data of all the forms in XML format
	 * @param objContext represents the form number
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */	
	public String wfValData(String currFrmXmlStr, String hdrFrmXmlStr,String allFrmXmlStr, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = "";

		try
		{			
			if(currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = parseString(currFrmXmlStr); 
			}
			if(hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = parseString(hdrFrmXmlStr); 
			}
			if(allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = parseString(allFrmXmlStr);
			}
			errString = wfValData(currDom,hdrDom,allDom,objContext,editFlag,xtraParams);
		}//end of try
		catch(Exception e)
		{
			System.out.println("Exception : [NearExpiryIC][wfValData(String currFrmXmlStr)] : ==>\n"+e.getMessage());
		}
		return (errString); 
	}

	/**
	 * The public overloaded method takes a document as input and is used for the validation of specified fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data as a document object model
	 * @param hdrDom contains all the header information
	 * @param allDom contains the field data of all the forms 
	 * @param objContext represents form number
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */	
	public String wfValData(Document currDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException 	
	{
		String errString = "";
		String columnValue = "";
		String sql = "";	
		String pickOrder = "";
		String itemCode = "";
		String pickType = "";
		String cartonNumber = "";
		String childNodeName = "";
		String errCode = "";
		String ptcn = "";
		String trfStatus = "";
		String confirmed = "";
		double pickissQuantity = 0;
		double pickordQuantity = 0;	
		int noOfChilds = 0;
		int noOfParent = 0;
		int count = 0;
		double quantity = 0d;
		int currLineNo = 0;
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();		
		GenericUtility genericUtility = GenericUtility.getInstance();

		try
		{			
			int currentFormNo = 0, cnt = 0;							
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");		
			DistCommon dComm = new DistCommon();		
			Node childNode =null;			
			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			if ( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}

			NodeList parentList = currDom.getElementsByTagName( "Detail" + currentFormNo );
			NodeList childList = null;	
			noOfParent = parentList.getLength();

			switch(currentFormNo)
			{
			//Changed by sumit on 28/03/13 adding validation for case 1 start
			case 1:
			{
				childList = parentList.item( 0 ).getChildNodes();
				noOfChilds = childList.getLength();
				for (int ctr = 0; ctr < noOfChilds; ctr++)
				{
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();						
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					
					if ( "pick_type".equalsIgnoreCase( childNodeName ) )
					{
						pickType = genericUtility.getColumnValue("pick_type",hdrDom);
						trfStatus = checkNull(genericUtility.getColumnValue("trf_status",hdrDom));
						confirmed = checkNull(genericUtility.getColumnValue("confirmed",hdrDom));
						System.out.println(" pickType ["+pickType+"] trfStatus ["+trfStatus+"] confirmed ["+confirmed+"]");
						if(!"A".equalsIgnoreCase(pickType))
						{							
							errString = itmDBAccessEJB.getErrorString("","INPICKTYPE",userId);
							return errString;
						}
						else if( "N".equalsIgnoreCase(confirmed))
						{
							errString = itmDBAccessEJB.getErrorString("","INVPIKNCON",userId);
							return errString;
						}
						else if( "Y".equalsIgnoreCase(trfStatus))
						{
							errString = itmDBAccessEJB.getErrorString("","INVPIKORD",userId);
							return errString;
						}
						
					}
				}
				//Changed by sumit on 28/03/13 adding validation for case 1 end
			}
			case 2:
			{
				childList = parentList.item( 0 ).getChildNodes();
				noOfChilds = childList.getLength();
				for (int ctr = 0; ctr < noOfChilds; ctr++)
				{	
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();						
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					pickOrder = genericUtility.getColumnValue("pick_order",hdrDom);
					System.out.println("PICKORD="+pickOrder);
					cartonNumber = genericUtility.getColumnValue("carton_no",currDom);					
					pickType = genericUtility.getColumnValue("pick_type",hdrDom);
					System.out.println("PICKTTYPE="+pickType);
					itemCode = genericUtility.getColumnValue("item_code",currDom);
					System.out.println("ITEMCODE="+itemCode);

					if ( "carton_no".equalsIgnoreCase( childNodeName ) )
					{
						cartonNumber = checkNull(genericUtility.getColumnValue("carton_no", currDom));
						System.out.println("cartonNumber = ["+cartonNumber.trim()+"]");
						if(cartonNumber == null || cartonNumber.trim().length() == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","NULCARTNNO",userId);
							return errString;
						}
						else
						{
							cartonNumber = cartonNumber.trim();
							System.out.println(" cartonNumber ***************** ["+cartonNumber+"]");
							sql = "SELECT CARTON_NO FROM CARTON_MASTER WHERE CARTON_NO = ?";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, cartonNumber);
							rs = pstmt.executeQuery();							
							if( !rs.next() )
							{
								errString = itmDBAccessEJB.getErrorString("","INVCTNNO1",userId);
								return errString; 
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							sql = " SELECT PTCN FROM WAVE_TASK_DET WHERE REF_ID = ? ";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, pickOrder );
							rs = pstmt.executeQuery();							
							if( rs.next() )
							{
								ptcn = rs.getString("PTCN");
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
	
							sql = " SELECT COUNT(CARTON_NO) FROM CARTON_MASTER WHERE PTCN = ? AND CARTON_TYPE = ? AND CARTON_NO = ? ";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, ptcn );
							pstmt.setString( 2, pickType);
							pstmt.setString( 3, cartonNumber);
							rs = pstmt.executeQuery();	
							if(rs.next())
							{
								count =  rs.getInt(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							
							if(count == 0) 
							{
								errCode = "INVCTNNO";
								errString = itmDBAccessEJB.getErrorString("","INVCTNNO",userId);
								return errString; 
							}
						}
					}
					
					else if ( "quantity".equalsIgnoreCase( childNodeName ) )
					{	
						String strQuantity = "";
						strQuantity = checkNull(genericUtility.getColumnValue("quantity",currDom));
						if(strQuantity.trim().length() == 0)
						{
							strQuantity = "0";
						}
						quantity = Double.parseDouble(strQuantity);
						currLineNo =Integer.parseInt(genericUtility.getColumnValue("line_no",currDom));
						System.out.println(" quantity ["+quantity+"]");
						if(quantity == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","INVQUANTIY",userId);
							return errString;
						}
						
						//Changed by sumit on 28/03/13 this validation will happen from pre save start
						/*sql = " SELECT SUM(QUANTITY) AS QUANTITY FROM PICK_ISS_DET WHERE PICK_ORDER = ? AND ITEM_CODE = ?  AND LINE_NO = ?";					  
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, pickOrder );
						pstmt.setString( 2, itemCode );
						pstmt.setInt( 3, currLineNo );
						
						rs = pstmt.executeQuery();							
						if( rs.next() )
						{
							pickissQuantity = rs.getDouble("QUANTITY");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						sql = " SELECT SUM(QUANTITY) 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() )
						{
							pickordQuantity = rs.getDouble("QUANTITY");
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						System.out.println("pickissQuantity["+ pickissQuantity+"]quantity["+quantity+"]");
						pickissQuantity = quantity + pickissQuantity;
						System.out.println("pickissQuantity["+pickissQuantity+"]pickordQuantity["+pickordQuantity+"][");
						
						if( pickissQuantity == pickordQuantity )
						{

						}
						else
						{
							errCode = "INVQNTY";
							errString = itmDBAccessEJB.getErrorString("","INVQNTY",userId);
							return errString; 
						}*/
						
						//Changed by sumit on 28/03/13 this validation will happen from pre save end
					}		
					//Changed by sumit on 28/03/13 this validation will happen from pre save end
				} // for loop end
			} //case 2 end
			} //switch end
		} //try block end
		catch(Exception e)
		{
			System.out.println("Exception in PickIssueEJB  == >");
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :PickIssueEJB:wfValData :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		return errString;
	}
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
}
