/**
 *  PURPOSE  : DefaultItemChanged for wave generation process
 *  AUTHOR   : Manohar
 *  Obj_name : w_despeditprc
 */


package ibase.webitm.ejb.wms;

import java.awt.print.PrinterJob;
import javax.print.PrintService;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;



import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.ejb.dis.SaleOrdItmGen;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class DespEditPrcIC extends ValidatorEJB implements WaveGenerationICRemote, WaveGenerationICLocal{
	
	/**
	* 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 containspoic_wavegen_default_data 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 :WaveGenerationIC :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from WaveGenerationIC 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
	{
		
		String siteCode = "";
		String errString = "";
		int currentFormNo = 0;
		String columnValue = "";
		String sSQL = "";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		StringBuffer valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n" );
		GenericUtility genericUtility = GenericUtility.getInstance();
		java.sql.Date dateFrom = null;
		String custCode = "", custCodeDlv = "";
		String saleOrder = "";
		String saleOrdTo = ""; //added by sumit on 19/11/12
		String saleOrdFrom = ""; //added by sumit on 19/11/12
		
		try
		{
			String applDateFmt = genericUtility.getApplDateFormat();
			String dbDateFmt = genericUtility.getDBDateFormat();
			
			ConnDriver connDriver = new ConnDriver(); 
			conn = connDriver.getConnectDB("DriverITM");
			siteCode = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginSiteCode");
			System.out.println("site code ->["+siteCode+"]");
			
			System.out.println("Current Column> > > > ->["+currentColumn+"]");
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			
			valueXmlString.append("</Header>\r\n" );
			
			switch ( currentFormNo )
			{
			  	case 1:
				{
								
					if ( currentColumn.trim().equalsIgnoreCase( "itm_default" ))
					{
						System.out.println("--------------item default --------------");
						valueXmlString.append( "<Detail1>\r\n" );
						valueXmlString.append( "<site_code><![CDATA[" ).append( siteCode ).append( "]]></site_code>\r\n" );
						valueXmlString.append( "<item_ser__fr><![CDATA[" ).append( "0" ).append( "]]></item_ser__fr>\r\n" );
						valueXmlString.append( "<item_ser__to><![CDATA[" ).append( "zz" ).append( "]]></item_ser__to>\r\n" );
						valueXmlString.append( "<item_code__fr><![CDATA[" ).append( "0" ).append( "]]></item_code__fr>\r\n" );
						valueXmlString.append( "<item_code__to><![CDATA[" ).append( "zz" ).append( "]]></item_code__to>\r\n" );
						valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__fr>\r\n" );
						valueXmlString.append( "<cust_code__to><![CDATA[" ).append( "zz" ).append( "]]></cust_code__to>\r\n" );
						valueXmlString.append( "<sale_order__fr><![CDATA[" ).append( "0" ).append( "]]></sale_order__fr>\r\n" );
						valueXmlString.append( "<sale_order__to><![CDATA[" ).append( "zz" ).append( "]]></sale_order__to>\r\n" );
						valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__dlv_fr>\r\n" );
						valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( "zz" ).append( "]]></cust_code__dlv_to>\r\n" );
						valueXmlString.append( "<lot_no__fr><![CDATA[" ).append( "0" ).append( "]]></lot_no__fr>\r\n" );
						valueXmlString.append( "<lot_no__to><![CDATA[" ).append( "zz" ).append( "]]></lot_no__to>\r\n" );
						valueXmlString.append( "</Detail1>\r\n" );
					}
					else if ( currentColumn.trim().equalsIgnoreCase( "sale_order__fr" ))
					{
							
						columnValue = genericUtility.getColumnValue("sale_order__fr",currDom);
						//Changed by sumit on 19/11/12 itemchanege in case of same saleorder 
						saleOrdTo = checkNull(genericUtility.getColumnValue("sale_order__to",currDom));
						valueXmlString.append( "<Detail1>\r\n" );
						if(columnValue != null && !columnValue.equalsIgnoreCase("0"))
						{
							
							sSQL = " SELECT S.CUST_CODE, S.CUST_CODE__DLV " +
									" FROM SORDER S WHERE SALE_ORDER = ? ";
							pstmt = conn.prepareStatement(sSQL);
							pstmt.setString(1,columnValue);
							rs=pstmt.executeQuery();
							
							if(rs.next())
							{
								custCode = rs.getString("CUST_CODE");
								custCodeDlv = rs.getString("CUST_CODE__DLV");
							}
							
							//Changed by sumit on 19/11/12 setting default value start. 
							/*valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( custCode ).append( "]]></cust_code__fr>\r\n" );
							valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_fr>\r\n" );
							valueXmlString.append( "<cust_code__to><![CDATA[" ).append( custCode ).append( "]]></cust_code__to>\r\n" );
							valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_to>\r\n" );*/
							if( columnValue.trim().equalsIgnoreCase(saleOrdTo.trim()))
							{
								valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( custCode ).append( "]]></cust_code__fr>\r\n" );
								valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_fr>\r\n" );
								valueXmlString.append( "<cust_code__to><![CDATA[" ).append( custCode ).append( "]]></cust_code__to>\r\n" );
								valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_to>\r\n" );
							}
							else
							{
								valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__fr>\r\n" );
								valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__dlv_fr>\r\n" );
								valueXmlString.append( "<cust_code__to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__to>\r\n" );
								valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__dlv_to>\r\n" );
							}
							//Changed by sumit on 19/11/12 setting default value end. 
							
							rs.close();
							rs=null;
							pstmt.close();
							pstmt=null;
						}
						valueXmlString.append( "</Detail1>\r\n" );
						
					}
					else if ( currentColumn.trim().equalsIgnoreCase( "sale_order__to" ))
					{
						columnValue = genericUtility.getColumnValue("sale_order__to",currDom);						
						//Changed by sumit on 19/11/12 itemchanege in case of same saleorder 
						saleOrdFrom = checkNull(genericUtility.getColumnValue("sale_order__fr",currDom));
						valueXmlString.append( "<Detail1>\r\n" );
						if(columnValue != null && !columnValue.equalsIgnoreCase("0"))
						{
							
							sSQL = " SELECT S.CUST_CODE, S.CUST_CODE__DLV " +
									" FROM SORDER S WHERE SALE_ORDER = ? ";
							pstmt = conn.prepareStatement(sSQL);
							pstmt.setString(1,columnValue);
							rs=pstmt.executeQuery();
							
							if(rs.next())
							{
								custCode = rs.getString("CUST_CODE");
								custCodeDlv = rs.getString("CUST_CODE__DLV");
							}
							//Changed by sumit on 19/11/12 setting default value start. 
							/*valueXmlString.append( "<cust_code__to><![CDATA[" ).append( custCode ).append( "]]></cust_code__to>\r\n" );
							valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_to>\r\n" );*/
							if(columnValue.trim().equalsIgnoreCase(saleOrdFrom.trim()))
							{
								
								valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( custCode ).append( "]]></cust_code__fr>\r\n" );
								valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_fr>\r\n" );							
								valueXmlString.append( "<cust_code__to><![CDATA[" ).append( custCode ).append( "]]></cust_code__to>\r\n" );
								valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( custCodeDlv ).append( "]]></cust_code__dlv_to>\r\n" );
							}
							else
							{
								valueXmlString.append( "<cust_code__fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__fr>\r\n" );
								valueXmlString.append( "<cust_code__dlv_fr><![CDATA[" ).append( "0" ).append( "]]></cust_code__dlv_fr>\r\n" );	
								valueXmlString.append( "<cust_code__to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__to>\r\n" );
								valueXmlString.append( "<cust_code__dlv_to><![CDATA[" ).append( "ZZ" ).append( "]]></cust_code__dlv_to>\r\n" );
							}
							rs.close();
							rs=null;
							pstmt.close();
							pstmt=null;
						}
						valueXmlString.append( "</Detail1>\r\n" );
					}
				}
				break;
			}
			valueXmlString.append( "</Root>\r\n" );
		}
		catch(Exception e)
		{
			System.out.println("Exception: WaveGenerationIC: defaultItemChanged(Document dom): " + e.getMessage() + ":");
			e.printStackTrace();
			errString = genericUtility.createErrorString(e);
			
		}
		
		return valueXmlString.toString();		
	}
	
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
	
	/**
	 * The method is defined without any parameter and returns blank string
	 */
	@Override
	public String wfValData() throws RemoteException, ITMException
	{
		return "";
	}

	/**
	 * The public method is used for converting the current form data into a document(DOM)
	 * The dom 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 xmlString contains the current form data in XML format
	 * @param xmlString1 contains all the header information in the XML format
	 * @param xmlString2 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
	 */	
	@Override
	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext,String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currFormDataDom = null;
		Document hdrDataDom = null;
		Document allFormDataDom = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();    

		try
		{
			System.out.println( "xmlString ::" + xmlString);
			System.out.println( "xmlString1 ::" + xmlString1);
			System.out.println( "xmlString2 ::" + xmlString2);
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				currFormDataDom = genericUtility.parseString(xmlString); 
			}
			if(xmlString1 != null && xmlString1.trim().length()!=0)
			{
				hdrDataDom = genericUtility.parseString(xmlString1); 
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				allFormDataDom = genericUtility.parseString(xmlString2); 
			}
			errString = wfValData( currFormDataDom, hdrDataDom, allFormDataDom, objContext, xtraParams);
			System.out.println( "ErrString: " + errString);
		}
		catch(Exception e)
		{
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return (errString); 
	}

	/**
	 * The public overloaded method takes a document as input and is used for the validation of required fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currFormDataDom contains the current form data as a document object model
	 * @param hdrDataDom contains all the header information
	 * @param allFormDataDom 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
	 */
	@Override
	public String wfValData(Document currFormDataDom, Document hdrDataDom, Document allFormDataDom, String objContext, String xtraParams) throws RemoteException, ITMException
	{   				
		String columnValue ="";
		String errString = "";
		String sql ="";
		String singleLot ="";
		String masterPackAllow = "";
		String activePickAllow = "";
		String stockToDockAllow = "";
		String custCode = "";
		//Changed by sumit on 03/10/12 
		String printer = "";
		
		int count = 0, cnt = 0;
		int rowCount = 0;
		int noOfChilds = 0;
		int noOfParent = 0;	

		GenericUtility genericUtility = GenericUtility.getInstance();		

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;		

		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");
		String errorType = "", errCode = "";
		ArrayList errList = new ArrayList();
		ArrayList errFields = new ArrayList();
		Set errSet = null;
		try
		{	
			int currentFormNo = 0;				
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "DriverITM" );
			connDriver = null;

			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );

			if ( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			NodeList parentList = currFormDataDom.getElementsByTagName( "Detail" + currentFormNo );
			NodeList childList = null;	
			noOfParent = parentList.getLength();		

			switch ( currentFormNo )  // Switch Case for form number
			{
			case 1:
			{	
				childList = parentList.item(0).getChildNodes();
				noOfChilds = childList.getLength();

				for ( int ctr = 0; ctr < noOfChilds; ctr++ ) //Loop for each node of current detail
				{	
					Node childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					String childNodeName = childNode.getNodeName();
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					if ( "active_pick_allow".equalsIgnoreCase( childNodeName ) )
					{
						activePickAllow = checkNull(genericUtility.getColumnValue( "active_pick_allow", currFormDataDom ));
						custCode = genericUtility.getColumnValue( "cust_code__from", currFormDataDom );
						if(activePickAllow.trim().length() > 0 )
						{
							sql = 	"SELECT C.SINGLE_LOT, W.MASTER_PACK_ALLOW, W.ACTIVE_PICK_ALLOW, W.STOCK_TO_DOCK_ALLOW " +
									"FROM CUSTOMER C, WAVE_TYPE W WHERE C.WAVE_TYPE = W.WAVE_TYPE AND C.CUST_CODE = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, custCode);
							rs = pstmt.executeQuery();
							if( rs.next())
							{								
								if( !activePickAllow.equalsIgnoreCase(rs.getString("ACTIVE_PICK_ALLOW")))
								{
									//errList.add( "CHACTPKALL" );
									errFields.add( childNodeName.toLowerCase() );
									errList.add( "CHSINGLELT" );
									//errFields.add( "" );
								}
							}
							if( rs != null )
							{
								rs.close();
								rs = null;
							}
							if( pstmt != null )
							{
								pstmt.close();
								pstmt = null;								
							}
						}
					}
				}
			} //End of case 1 Validation
			break;				
					
			}//End of switch statement
			errSet = new HashSet(errList);
			errList = new ArrayList(errSet);
			int errListSize = errList.size();
			cnt =0;
			String errFldName = null;
			if ( errList != null && errListSize > 0 )
			{
				for (cnt = 0; cnt < errListSize; cnt++ )
				{
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					System.out.println("errCode .........."+errCode);
					//String errMsg = hashMap.get(errCode)!=null ? hashMap.get(errCode).toString():"";
					//System.out.println("errMsg .........."+errMsg);
					errString = getErrorString( errFldName, errCode, userId );
					errorType =  errorType( conn , errCode );
					if ( errString.length() > 0)
					{
						String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
						bifurErrString =bifurErrString;//+"<trace>"+errMsg+"</trace>";
						bifurErrString =bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						System.out.println("errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;

				errStringXml.append("</Errors></Root>\r\n");
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
		}
		catch ( Exception e )
		{
			System.out.println ( "Exception: WaveGenerationIC: wfValData( Document currFormDataDom ): " + e.getMessage() + ":" );
			//throw new ITMException(e);
			e.printStackTrace();			
		}
		finally
		{
			try
			{
				if (rs!=null)
				{
					rs.close();
					rs = null;
				}				
				
				if( conn != null  )
				{
					conn.close(); conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception : WaveGenerationIC:wfValData : " + e.getMessage() );
				throw new ITMException(e);
			}
		}
		System.out.println( "errString>>>>>>>::"+errString );
		return errString;
	}
	private String errorType( Connection conn , String errorCode )
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO =   ? ";

			pstmt = conn.prepareStatement( sql );			
			pstmt.setString(1, errorCode);			
			rs = pstmt.executeQuery();
			while( rs.next() )
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}		
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}
		}		
		return msgType;
	}
}
