/**
* PURPOSE : Validation and Item Change implementation for NearExpiryPrc component .
* AUTHOR  : BALU
* Date    : 19/09/2011
* 
*/

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 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 NearExpiryIC extends ValidatorEJB implements NearExpiryICRemote, NearExpiryICLocal  
{
	// 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 refSer = "";
		String locCodeTo = "";
		String tranDate = "";
		String singleLotSl = "";
		String itemLotOpt = "";
		String rowCountStr = "";
		String itemCode = "";
		String siteCode = "";
		String lotNo = "";
		String lpnNo = "";
		String childNodeName = "";
		String expLock = "";
		String nexpLock = "";
		String lockORTransfer = "";

		int noOfChilds = 0;
		int noOfParent = 0;
		int count = 0;

		double quantity = 0d;

		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		
        GenericUtility genericUtility = GenericUtility.getInstance();
        
		try
		{
			
			int currentFormNo = 0, cnt = 0;		
					
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			
			DistCommon dComm = new DistCommon();

			lockORTransfer = dComm.getDisparams("999999","LOCK_OR_TRANSFER",conn);
			
			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)
			{
				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 ( "lock_code_exp".equalsIgnoreCase( childNodeName ) )
						{
							if ( "T".equalsIgnoreCase(lockORTransfer.trim()) )
							{
								sql = "SELECT COUNT(*) AS COUNT FROM LOCATION WHERE LOC_CODE = ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, columnValue );
								rs = pstmt.executeQuery();
								
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								rs.close(); rs = null;
								pstmt.close(); pstmt = null;

								if( count == 0 )
								{
									errString = getErrorString( "lock_code_exp", "INVLOCCODE", userId );
									break;
								}
							}
							else if ( "L".equalsIgnoreCase(lockORTransfer.trim()) )
							{
								sql = "SELECT COUNT(*) AS COUNT FROM INV_LOCK WHERE LOCK_CODE = ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, columnValue );
								rs = pstmt.executeQuery();
								
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								rs.close(); rs = null;
								pstmt.close(); pstmt = null;

								if( count == 0 )
								{
									errString = getErrorString( "lock_code_exp", "INVLOCKCD", userId );
									break;
								}
							}
							else
							{
								errString = getErrorString( "lock_code_exp", "INVDISPARM", userId );
								break;
							}
						}
						else if ( "lock_code_nexp".equalsIgnoreCase( childNodeName ) )
						{
							if ( "T".equalsIgnoreCase(lockORTransfer.trim()) )
							{
								sql = "SELECT COUNT(*) AS COUNT FROM LOCATION WHERE LOC_CODE = ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, columnValue );
								rs = pstmt.executeQuery();
								
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								rs.close(); rs = null;
								pstmt.close(); pstmt = null;

								if( count == 0 )
								{
									errString = getErrorString( "lock_code_nexp", "INVLOCCODE", userId );
									break;
								}
							}
							else if ( "L".equalsIgnoreCase(lockORTransfer.trim()) )
							{
								sql = "SELECT COUNT(*) AS COUNT FROM INV_LOCK WHERE LOCK_CODE = ? ";
								pstmt = conn.prepareStatement( sql );
								pstmt.setString( 1, columnValue );
								rs = pstmt.executeQuery();
								
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								rs.close(); rs = null;
								pstmt.close(); pstmt = null;

								if( count == 0 )
								{
									errString = getErrorString( "lock_code_nexp", "INVLOCKCD", userId );
									break;
								}
							}
							else
							{
								errString = getErrorString( "lock_code_nexp", "INVDISPARM", userId );
								break;
							}
						}
						else if( "site_code".equalsIgnoreCase( childNodeName ) )
						{
							if ( childNode.getFirstChild() == null)
							{
								errString = getErrorString( "site_code", "NULLSITE", userId );
								break;
							}
							siteCode = genericUtility.getColumnValue( "site_code", currDom );
							sql = "SELECT COUNT(*) AS COUNT FROM SITE WHERE SITE_CODE = ?";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, siteCode );
							rs = pstmt.executeQuery();
							
							if( rs.next() )
							{
								count = rs.getInt("COUNT");
							}
							rs.close(); rs = null;
							pstmt.close(); pstmt = null;

							if( count == 0 )
							{
								errString = getErrorString( "site_code", "INVDSITECD", userId );
								break;
							}
						}//End of site_code validation
					}// for loop end
				}//case 1 end
			} //switch end
		}//try block end
		catch(Exception e)
		{
			System.out.println("Exception in NearExpiryIC  == >");
			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 :NearExpiryIC:wfValData :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		return errString;
	}

	/**
	* The public method is defined without any parameters and returns blank string
	*/
	public String itemChanged() 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 currentColumn represents the value of current field.
	* @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 itemChanged(String currFrmXmlStr, String hdrFrmXmlStr, String allFrmXmlStr, 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 (currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currFrmXmlStr); 
			}
			if (hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrFrmXmlStr); 
			}
			if (allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allFrmXmlStr); 
			}
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception : NearExpiryIC:defaul_ItemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from NearExpiryIC default_Itemchanged" );
		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 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 currentColumn represents the current field 
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information
	 * 
	 */
	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String sql = "";
		String expLock = "";
		String nexpLock = "";
		String siteDescr = "";
		String lockORTransfer = "";
		String disparmVal1 = "";
		String disparmVal2 = "";
		
				
		int currentFormNo = 0;
		int domID = 0;
		
		double quantity = 0d; 
			
		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
				
		StringBuffer valueXmlString = new StringBuffer();		
		
		System.out.println("hello:");
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{
			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			String siteCode = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginSiteCode" );
			
			DateFormat dateFormat = new SimpleDateFormat(genericUtility.getApplDateFormat());
			String dbDateFormat = genericUtility.getDBDateFormat();
			String applDateFormat = genericUtility.getApplDateFormat();

			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
            valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
            valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n" );

			switch ( currentFormNo )
			{
			  	case 1:
				{
					valueXmlString.append( "<Detail1 domID='1'>\r\n" );
					if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
					{	
						DistCommon dComm = new DistCommon();
						lockORTransfer = dComm.getDisparams("999999","LOCK_OR_TRANSFER",conn);
						if ( "T".equalsIgnoreCase(lockORTransfer.trim()) )//For Transger
						{
							disparmVal1 = dComm.getDisparams("999999","NEAREXP_LOC",conn);
							disparmVal2 = dComm.getDisparams("999999","EXP_LOC",conn);
						}
						else if ( "L".equalsIgnoreCase(lockORTransfer.trim()) )//For Locking
						{
							disparmVal1 = dComm.getDisparams("999999","NEAR_EXP_LOCK",conn);
							disparmVal2 = dComm.getDisparams("999999","EXP_LOCK",conn);
						}

						valueXmlString.append( "<lock_code_exp><![CDATA[" ).append( disparmVal2 ).append( "]]></lock_code_exp>\r\n" );
						valueXmlString.append( "<lock_code_nexp><![CDATA[" ).append( disparmVal1 ).append( "]]></lock_code_nexp>\r\n" );
						valueXmlString.append( "<site_code><![CDATA[" ).append( siteCode ).append( "]]></site_code>\r\n" );

						sql = "SELECT DESCR FROM SITE WHERE SITE_CODE = ?";
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, siteCode );						
						rs = pstmt.executeQuery();	
						if( rs.next() )
						{
							siteDescr = rs.getString("DESCR");
						}
						rs.close();rs = null;
						pstmt.close();pstmt = null;
						valueXmlString.append( "<site_descr><![CDATA[" ).append( siteDescr ).append( "]]></site_descr>\r\n" );
					}
					valueXmlString.append("</Detail1>\r\n");
				}//case 1 end here
			}//switch  end
		}//try block end
		catch(Exception e)
		{
			System.out.println( "Exception :NearExpiryIC :default_ItemChanged(Document,String):" + e.getMessage() + ":" );
			valueXmlString = valueXmlString.append( genericUtility.createErrorString( e ) );
		}
		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 :NearExpiryIC:default_ItemChanged :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		valueXmlString.append( "</Root>\r\n" );	
		System.out.println( "\n****ValueXmlString :" + valueXmlString.toString() + ":********" );
		return valueXmlString.toString();
	}
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
}
