/**
 * PURPOSE : Validation and Itemchange for Check sheet verification
 * AUTHOR : Kunal Mandhre
 * DATE : 11/06/2012
 */

package ibase.webitm.ejb.wms;

import java.awt.print.PrinterJob;
import java.rmi.RemoteException;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.print.PrintService;

import org.w3c.dom.*;
import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class CheckSheetPrintIC extends ValidatorEJB implements CheckSheetPrintICLocal,CheckSheetPrintICRemote 
{
	/**
	 * 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 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
	 */	
	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
	 */
	public String wfValData(Document currFormDataDom, Document hdrDataDom, Document allFormDataDom, String objContext, String xtraParams) throws RemoteException, ITMException
	{   				
		String shipmentId = "";
		String cartonNo = "";
		String replOrder = "";
		String columnValue = "";			
		String errString = "";
		String sql = "";
		String confirmed = "";
		String tranCode = "";
		String serviceCode = "";
		int count = 0;
		int noOfChilds = 0;
		int noOfParent = 0;
		int cnt = 0;
		String printer = "";
		String palletNo = "";

		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 = "";
		ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();		
		String palletID = "";
		String ptcn = ""; 
		try
		{	
			System.out.println("call wf valdata::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::;");
			int currentFormNo = 0;				
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "DriverValidator" );

			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 + "]");

					palletID = checkNull(genericUtility.getColumnValue( "pallet_id", currFormDataDom ));
					ptcn = checkNull(genericUtility.getColumnValue( "ptcn", currFormDataDom ));
					printer = checkNull(genericUtility.getColumnValue( "printer_name", currFormDataDom ));
					System.out.println("palletID [" + palletID + "]");
					System.out.println("ptcn [" + ptcn + "]");
					System.out.println("printer ["+printer+"]");

					if( ( palletID == null || palletID.trim().length() == 0) && ( ptcn == null || ptcn.trim().length() == 0) )  
					{
						errString = itmDBAccessEJB.getErrorString("","VTPTCNPALT",userId);
						return errString; 
					}

					if( palletID !=null && palletID.trim().length() > 0 )
					{
						sql = " SELECT COUNT(*) FROM PALLET_NO WHERE PALLET_NO = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, palletID);
						rs = pstmt.executeQuery();
						if( rs.next())
						{
							count = rs.getInt(1);
							System.out.println("count["+count+"]");
						}
						if(count == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","VTINVPALLT",userId);
							return errString; 
						}
						pstmt.close();pstmt = null;
						rs.close(); rs = null;							
					}

					if( ptcn !=null && ptcn.trim().length() > 0 )
					{
						sql = " SELECT COUNT(*) FROM WAVE_TASK_DET WT, WAVE_TASK W WHERE W.WAVE_ID = WT.WAVE_ID AND WT.PTCN = ? AND W.CANCEL = 'N' ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, ptcn);
						rs = pstmt.executeQuery();
						if( rs.next())
						{
							count = rs.getInt(1);
							System.out.println("count1["+count+"]");
						}
						System.out.println("Before Validation count : "+count);
						if(count == 0)
						{
							System.out.println("inside error code count : "+count);
							errString = itmDBAccessEJB.getErrorString("","VTINVDPTCN",userId);
							return errString; 
						}	
						System.out.println("after Validation count : "+count);
						pstmt.close();pstmt = null;
						rs.close(); rs = null;			
					}

					if( printer == null || printer.length() == 0 )					
					{
						errString = itmDBAccessEJB.getErrorString("","VTPRNTBLNK",userId);
						return errString; 
					}
					if( printer != null && printer.length() > 0 )
					{
						sql = " SELECT COUNT(*) FROM NET_PRINTERS WHERE PRINTER_NAME = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, printer.trim());
						rs = pstmt.executeQuery();
						if( rs.next())
						{
							count = rs.getInt(1);
							System.out.println("count2["+count+"]");
						}
						if(count == 0)
						{
							errString = itmDBAccessEJB.getErrorString("","VTINVPRINT",userId);
							return errString; 
						}
						pstmt.close();pstmt = null;
						rs.close(); rs = null;			
					}
				}
			} //End of case 1 Validation
			break;	
			}
		}
		catch ( Exception e )
		{
			System.out.println ( "Exception: CheckSheetIC: wfValData( Document currFormDataDom ): " + e.getMessage() + ":" );
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs!=null)
				{
					rs.close();
					rs = null;
				}				
				if (pstmt!=null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null  )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception : CheckSheetIC:wfValData : " + e.getMessage() );
				throw new ITMException(e);
			}
		}
		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;
	}
	private String checkNull( String input )	
	{
		if ( input == null )
		{
			input = "";
		}
		return input;
	}		
}
