/**
* PURPOSE : Validation & ItemChanged for Despatch Pack
* 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 org.w3c.dom.*;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class DespPackIC extends ValidatorEJB implements DespPackICRemote, DespPackICLocal{
	
	/**
	* The method defined with no parameter and returns nothing
	*/
	public String wfValData() throws RemoteException, ITMException
	{
		return "";
	}
	
	/**
	 * The public method is used for validation of required fields which return called overloaded method
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currXmlDataStr contains the current form data in XML format
	 * @param hdrXmlDataStr contains always header form data in XML format
	 * @param allXmlDataStr contains all forms data in XML format 
	 * @param objContext represents form no
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	*/ 
	
	public String wfValData(String currXmlDataStr, String hdrXmlDataStr, String allXmlDataStr, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if(currXmlDataStr != null && currXmlDataStr.trim().length()!= 0)
			{
				System.out.println ( "currXmlDataStr: " + currXmlDataStr);
				currDom = genericUtility.parseString(currXmlDataStr); 
			}
			if(hdrXmlDataStr != null && hdrXmlDataStr.trim().length()!= 0)
			{
				hdrDom = genericUtility.parseString(hdrXmlDataStr); 
			}
			if(allXmlDataStr != null && allXmlDataStr.trim().length()!= 0)
			{
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = wfValData( currDom, hdrDom, allDom, objContext, editFlag, xtraParams );
			System.out.println ( "ErrString: DespPackIC" + errString);
		}
		catch(Exception e)
		{
			System.out.println ( "Exception: DespPackIC: wfValData(String currXmlDataStr): " + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println ( "Returning from DespPackIC wfValData" );
		return ( errString ); 
	}
	
	/**
	 * The public overloaded method is used for validation of required fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data 
	 * @param hdrDom contains always header form data
	 * @param allDom contains all forms data 
	 * @param objContext represents form no
	 * @param editFlag the mode of the 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 userId = "",errString= "", outerCartonNo = "";
		Connection conn = null;		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
      	NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		String despId = null;
		String sql = null;
		//String tranSer = "";
        int count = 0;
        int ctr = 0;
		int noOfChilds = 0;
		int currentFormNo = 0;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			parentList = currDom.getElementsByTagName("Detail" + currentFormNo);
			parentNode = parentList.item(0);
			childList = parentNode.getChildNodes();
			noOfChilds = childList.getLength();
			for(ctr = 0; ctr < noOfChilds; ctr++)
			{
				childNode = childList.item(ctr);
				childNodeName = childNode.getNodeName();
				switch(currentFormNo)
				{           
					case 1:
						if(childNodeName.equalsIgnoreCase("desp_id"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("desp_id","NULLDESPCD",userId);
								break;
							}
							else
							{
								sql = "SELECT COUNT(*) AS COUNT FROM DESPATCH WHERE DESP_ID = ?";
								despId = checkNull( genericUtility.getColumnValue("desp_id",currDom) );
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, despId );
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								if( count == 0 )
								{
									errString = getErrorString("desp_id","INVDESPEXT",userId);
									break;
								}
								if(rs != null )
								{
									rs.close();
									rs = null;
								}
								if(pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
							}
							
						}
						
					break;
					case 2:
						if(childNodeName.equalsIgnoreCase("outer_carton_no"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("outer_carton_no","NULLOUTCRN",userId);
								break;
							}
							else
							{
								sql = "SELECT COUNT(OUTER_CARTON_NO) AS COUNT FROM PACK_DET WHERE OUTER_CARTON_NO = ? ";
								outerCartonNo = checkNull( genericUtility.getColumnValue("outer_carton_no",currDom) );
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, outerCartonNo);
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								if( count == 0 )
								{
									errString = getErrorString("outer_carton_no","INVOUTCRNO",userId);
									break;
								}
								if(rs != null )
								{
									rs.close();
									rs = null;
								}
								if(pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
							}
							
						}
						
					break;
					
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception: DespPack: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (pstmt != null)
					{
						if (rs != null)
						{
							rs.close();
						}
						pstmt.close();
					}
					conn.close();
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}// End Finally
		return (errString);

    }
	
	
	/**
	* The method defined with no parameter and returns nothing
	*/
	public String itemChanged() throws RemoteException, ITMException
	{
		return "";
	}
	
	
	/**
	 * The public method is used for itemchange of required fields which return called overloaded method
	 * Returns itemchange string in XML format
	 * @param currXmlDataStr contains the current form data in XML format
	 * @param hdrXmlDataStr contains always header form data in XML format
	 * @param allXmlDataStr contains all forms data in XML format 
	 * @param objContext represents form no
	 * @param currentColumn represent Current COlumn
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm 
etc
	*/
	public String itemChanged(String currXmlDataStr, String hdrXmlDataStr, String allXmlDataStr, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if (currXmlDataStr != null && currXmlDataStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currXmlDataStr); 
			}
			if (hdrXmlDataStr != null && hdrXmlDataStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrXmlDataStr); 
			}
			if (allXmlDataStr != null && allXmlDataStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = defaultItemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :DespPackIC :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from DespPackIC itemChanged" );
		return errString;
	}// end ItemChanged Method
	
	/**
	 * The public overloaded method is used for itemchange of required fields 
	 * Returns itemchange string in XML format
	 * @param currDom contains the current form data 
	 * @param hdrDom contains always header form data
	 * @param allDom contains all forms data 
	 * @param objContext represents form no
	 * @param editFlag the mode of the transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
    */
	public String defaultItemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		
		Connection conn = null;		
		PreparedStatement pstmt = null, pstmt1 = null;
		ResultSet rs = null, rs1 = null;
		String errString = "";
		String sql = "";
		String outerCartonNo = "";
		String despId = "";
		String tranId = "";
		String siteCode = "", saleOrder = "";
		String itemCode = "",locCode = "",lotNo = "", lotSl = "";
		String locCodeTo = "";
		
		int  lineNo = 0;
		int noArt = 0;
		int lineNoSord = 0;
		int quantity = 0;
		int currentFormNo = 0, count = 0;
		StringBuffer valueXmlString = new StringBuffer();
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{
				
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("Driver");
			
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			
			//coding of item default
			despId  = genericUtility.getColumnValue("desp_id",hdrDom);
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n" );
			valueXmlString.append("</Header>\r\n" );
			
			switch ( currentFormNo )
			{
			  	case 2:
				{
								
					if ( currentColumn.trim().equalsIgnoreCase( "itm_default" ))
					{	
						
						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.LOC_CODE__TO, P.OUTER_CARTON_NO, P.NO_ART " +
								"FROM PACK_DET P, WAVE_TASK_DET W, DESPATCH D " +
								"WHERE D.DESP_ID = ? " +
								"AND D.WAVE_ID = W.WAVE_ID " +
								"AND P.TRAN_ID = W.REF_ID "; 				
								
						pstmt = conn.prepareStatement(sql);
						despId = setChar(despId);			
						pstmt.setString(1, despId);
						rs = pstmt.executeQuery();			
						System.out.println("Query Executed");
						
						while (rs.next())
						{
							lineNo++;
							tranId = rs.getString(1);
							lineNo = rs.getInt(2);
							saleOrder = rs.getString(3);					
							lineNoSord = rs.getInt(4);
							siteCode = rs.getString(5);					
							itemCode = rs.getString(6);					
							locCode = rs.getString(7);					
							lotNo = rs.getString(8);					
							lotSl = rs.getString(9);					
							quantity = rs.getInt(10);					
							locCodeTo = rs.getString(11);					
							outerCartonNo = rs.getString(12);					
							noArt = rs.getInt(13);
							// new changes
							 sql = "";
							 sql = "SELECT COUNT(OUTER_CARTON_NO) AS COUNT FROM DESP_PACK_DET WHERE OUTER_CARTON_NO = ?  AND DESP_ID=?";
							 pstmt1 = conn.prepareStatement(sql);
							 pstmt1.setString(1, outerCartonNo );
							 pstmt1.setString(2, despId );
							 
								rs1 = pstmt1.executeQuery();
								pstmt1.clearParameters();
								
								if( rs1.next() )
								{
									count = rs1.getInt("COUNT");
								}
								if( count == 0 )
								{
									System.out.println("Inside Not Existing Records despatch###########");
									valueXmlString.append( "<Detail2 domID='"+lineNo+"'>\r\n" );									
									/*valueXmlString.append( "<tran_id><![CDATA[" ).append( "" ).append( "]]></tran_id>\r\n" );*/
									valueXmlString.append( "<line_no protect ='1'><![CDATA[" ).append( lineNo  ).append( "]]></line_no>\r\n" );
					                valueXmlString.append( "<outer_carton_no protect ='1'><![CDATA[" ).append( checkNull(outerCartonNo ) ).append( "]]></outer_carton_no>\r\n" );
					                valueXmlString.append( "<desp_id protect ='1'><![CDATA[" ).append( checkNull(despId ) ).append( "]]></desp_id>\r\n" );
					                valueXmlString.append( "<track_no><![CDATA[" ).append( "" ).append( "]]></track_no>\r\n" );
					                valueXmlString.append( "</Detail2>\r\n" );	
								}
								else
								{					                
									System.out.println("Inside  Existing Records despatch************");
					                System.out.println("inside if when count != 0 ");
									valueXmlString.append( "<Detail2 domID='"+lineNo+"' objContext = '"+currentFormNo+"' objName=\"desp_det\" selected=\"Y\">\r\n" );
									//valueXmlString.append( "<attribute selected=\"Y\"/>\r\n" );
									/*valueXmlString.append( "<tran_id><![CDATA[" ).append( "" ).append( "]]></tran_id>\r\n" ); */
									valueXmlString.append( "<line_no protect ='1'><![CDATA[" ).append( lineNo  ).append( "]]></line_no>\r\n" );
					                valueXmlString.append( "<outer_carton_no protect ='1'><![CDATA[" ).append( checkNull(outerCartonNo ) ).append( "]]></outer_carton_no>\r\n" );
					                valueXmlString.append( "<desp_id protect ='1'><![CDATA[" ).append( checkNull(despId ) ).append( "]]></desp_id>\r\n" );
					                valueXmlString.append( "<track_no><![CDATA[" ).append( "" ).append( "]]></track_no>\r\n" );
					                valueXmlString.append( "</Detail2>\r\n" );	
								}
								
								if(pstmt1 !=null) pstmt1.close();
								if(rs1 != null ) rs1.close();
								
									
						}							
						
						if(rs != null )
						{
							rs.close();
							rs = null;
						}
						if(pstmt != null )
						{
							pstmt.close();
							pstmt = null;
						}				
		                                
					}
				}
				break;
			}
			
			valueXmlString.append( "</Root>\r\n" );			
		}
		catch(Exception e)
		{
			System.out.println("Exception: DespPackIC: itemchanged(Document dom): " + e.getMessage() + ":");
			e.printStackTrace();
			errString = genericUtility.createErrorString(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (pstmt != null)
					{
						if (rs != null)
						{
							rs.close();
						}
						pstmt.close();
					}
					conn.close();
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}// End Finally
		
		return valueXmlString.toString();
	}// END itemChanged 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);
    }

}
