/*
*	PURPOSE : Validation  and itemChanged
*   Author: Sandesh
*	Date:	08/08/11
*/

package ibase.webitm.ejb.wms;

import ibase.ejb.*;
import ibase.utility.*;
import ibase.system.config.*;
import ibase.utility.BaseLogger;
import ibase.webitm.ejb.*;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

import java.lang.*;
import java.io.*;
import java.rmi.RemoteException;
import java.sql.*;
import javax.ejb.*;
import java.text.*;
import java.util.Date;
import java.util.regex.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;

@javax.ejb.Stateless
public class LockGroupIC extends ValidatorEJB implements LockGroupICRemote,LockGroupICLocal 
{	
	
	/**
	* The method is defined with no paramters 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 contais 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 dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{			
			if(xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString); 
			}
			if(xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = genericUtility.parseString(xmlString1); 
			}
			if(xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = genericUtility.parseString(xmlString2); 
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
			System.out.println ( "ErrString: " + errString);
		}
		catch(Exception e)
		{
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
			throw new ITMException(e);
		}
		return errString; 
	}
	public String wfValData(Document dom, Document dom1, Document dom2, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException
	{   
		System.out.println("*****************Inside wfValData of LockGroupIC*****************");
				
		String groupCode = "";
		String lockCode = "";
		String groupDescr = "";
		String columnValue = "";
		String errString = "";
		String sql = "";

		int count = 0;
		
		Connection connectionObject = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try
		{	
			int currentFormNo = 0;	
            
            GenericUtility genericUtility = GenericUtility.getInstance();
		    DateFormat dtFormat = new SimpleDateFormat(genericUtility.getApplDateTimeFormat());
 			
			ConnDriver connDriver = new ConnDriver();
			connectionObject = connDriver.getConnectDB( "DriverValidator" );	
			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			
			if ( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			NodeList parentList = dom.getElementsByTagName( "Detail" + currentFormNo );
			NodeList childList = parentList.item( 0 ).getChildNodes();			
			int noOfChilds = childList.getLength();
			for (int ctr = 0; ctr < noOfChilds; ctr++)
			{	
				Node childNode = childList.item( ctr );
				String childNodeName = childNode.getNodeName();
				if ( childNode != null && childNode.getFirstChild() != null )
				{
					columnValue = childNode.getFirstChild().getNodeValue();
				}
				System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
				
				if ( "lock_group".equalsIgnoreCase( childNodeName ) && editFlag != null && editFlag.trim().equalsIgnoreCase("A") )
				{
					groupCode = checkNull(genericUtility.getColumnValue( "lock_group", dom));
					if( groupCode.trim().length() == 0 )
					{
						errString = getErrorString( "lock_group", "NULLGRPCD", userId );
						break;
					}
					else
					{
						if ( groupCode.trim().indexOf(" ") > 0 )
						{
							errString = getErrorString("lock_group","INVGRUPCD",userId);
							break;
						}
						boolean isValid = isValidData(groupCode);
						if ( !isValid )
						{
							errString = getErrorString("lock_group","INVGRUPCD",userId);
							break;
						}

						lockCode = checkNull(genericUtility.getColumnValue( "lock_code", dom));
						if ( lockCode.length() > 0 )
						{
							sql = "SELECT COUNT(*) AS COUNT FROM LOCK_GROUP WHERE LOCK_GROUP = ? AND LOCK_CODE = ? ";
							pstmt = connectionObject.prepareStatement( sql );
							pstmt.setString( 1, groupCode );
							pstmt.setString( 2, lockCode );
							rs = pstmt.executeQuery();
							if( rs.next() )
							{
								count = rs.getInt("COUNT");
							}
							if( count > 0 )
							{
								errString = getErrorString( "lock_group", "UNQGRPLOCK", userId );
								break;
							}
						}
					}
				}
				else if( "group_descr".equalsIgnoreCase( childNodeName ) )
				{
					groupDescr = checkNull(genericUtility.getColumnValue( "group_descr", dom));
					if( groupDescr.trim().length() == 0 )
					{
						errString = getErrorString( "group_descr", "NULGRPDESC", userId );
						break;
					}
				}
				else if( "lock_code".equalsIgnoreCase( childNodeName ) && editFlag != null && editFlag.trim().equalsIgnoreCase("A") )
				{
					lockCode = checkNull(genericUtility.getColumnValue( "lock_code", dom));
					if( lockCode.trim().length() == 0 )
					{
						errString = getErrorString( "lock_code", "NULLLOCKCD", userId );
						break;
					}
					sql = "SELECT COUNT(*) COUNT FROM INV_LOCK WHERE LOCK_CODE = ?";
					pstmt = connectionObject.prepareStatement( sql );
					pstmt.setString( 1, lockCode );
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						count = rs.getInt("COUNT");
					}
					if ( count == 0 )
					{
						errString = getErrorString( "lock_code", "LOCKNOTEXT", userId );
						break;
					}
					if( rs != null)
					{
						rs.close();
						rs = null;
					}
					if( pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
					groupCode = checkNull(genericUtility.getColumnValue( "lock_group", dom));
					if ( groupCode.length() > 0 )
					{
						sql = "SELECT COUNT(*) AS COUNT FROM LOCK_GROUP WHERE LOCK_GROUP = ? AND LOCK_CODE = ? ";
						pstmt = connectionObject.prepareStatement( sql );
						pstmt.setString( 1, groupCode );
						pstmt.setString( 2, lockCode );
						rs = pstmt.executeQuery();
						if( rs.next() )
						{
							count = rs.getInt("COUNT");
						}
						if( count > 0 )
						{
							errString = getErrorString( "lock_code", "UNQGRPLOCK", userId );
							break;
						}
					}
					if( rs != null)
					{
						rs.close();
						rs = null;
					}
					if( pstmt != null)
					{
						pstmt.close();
						pstmt = null;
					}
				}
			}
		}
		catch (Exception e)
		{
			System.out.println ( "Exception: wfValData(Document dom): " + e.getMessage() + ":" );
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				if( connectionObject != null )
				{
					connectionObject.close();
					connectionObject = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :wfValData :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		return (errString);
	}
	/*********************item change*********************/
	/**
	* The method is defined with no paramters 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 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 contais additional information such as loginEmpCode,loginCode,chgTerm etc
	*/

	public String itemChanged(String xmlString, String xmlString1, String xmlString2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		String errString = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			if (xmlString != null && xmlString.trim().length()!=0)
			{
				dom = genericUtility.parseString(xmlString); 
			}
			if (xmlString1 != null && xmlString1.trim().length()!=0)
			{
				dom1 = genericUtility.parseString(xmlString1); 
			}
			if (xmlString2 != null && xmlString2.trim().length()!=0)
			{
				dom2 = genericUtility.parseString(xmlString2); 
			}
			System.out.println ( "Calling  itemChanged( dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams ):");
			errString = itemChanged( dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :itemChanged(String,String):" + e.getMessage() + ":" );
			throw new ITMException(e);
		}
		System.out.println ( "returning from itemChanged \n["+errString+"]" );

		return errString;
	}
	
	public String itemChanged( Document dom, Document dom1, Document dom2, String objContext, String currentColumn,String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String userId = "" ;
	    String sql = "" ;
		String retString ="";
		String columnValue = "";
		String lockCode = "";
		String descr = "";

	    int currentFormNo = 0;
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		
		
		StringBuffer valueXmlString = new StringBuffer();
		
		try
		{
		    GenericUtility genericUtility = GenericUtility.getInstance();
		    
			ConnDriver connDriver = new ConnDriver();
			conn = connDriver.getConnectDB( "DriverValidator" );
			userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			columnValue = genericUtility.getColumnValue( currentColumn, dom );
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			System.out.println("current form no["+currentFormNo+"]");
			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>").append( editFlag );
			valueXmlString.append("</editFlag>\r\n</Header>\r\n");
			valueXmlString.append( "<Detail1 domID='1'>\r\n" );
					 
			if( currentColumn.trim().equalsIgnoreCase( "lock_code" ) )
			{
				lockCode = checkNull(genericUtility.getColumnValue( currentColumn , dom ));
				sql = "SELECT DESCR FROM INV_LOCK WHERE LOCK_CODE = ?";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1,lockCode);
				rs = pstmt.executeQuery();
				if( rs.next() )
				{
					descr = rs.getString("DESCR");
				}
				if( rs != null )
				{
					rs.close();
					rs = null;
				}
				if( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
				valueXmlString.append( "<lock_descr><![CDATA[" ).append( descr ).append( "]]></lock_descr>\r\n" );
			} 

			valueXmlString.append( "</Detail1>\r\n" );
            valueXmlString.append( "</Root>" );
			retString = valueXmlString.toString();
		} // end of try
		catch (Exception e)
		{
			e.printStackTrace();
			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 e1)
			{
				e1.printStackTrace();
				throw new ITMException(e1);
			}
		}
		System.out.println("====>from itemchage()\n---------------\n"+retString);
		return retString;
	} //end of function
	/**
	 * The private method is used for checkNull of input fields 
	 * Returns empty string if the input value is null otherwise the input value as it is
	 * @param inputVal represents input value to check
	 */
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
	/** isValidData: Validate input data using Java regex. 
	* This method checks if the input string is a valid data. 
	* @param dataStr String. data to validate 
	* @return boolean: true if data is valid, false otherwise. 
	* @auther Gulzar on 10/08/11
	*/  
	private boolean isValidData( String dataStr )
	{
		//Define pattern string
		String dataPattern ="^[a-zA-Z0-9]+[a-zA-Z0-9-_]+[a-zA-Z0-9 ]{1,}$";

		//compile pattern string
		Pattern p = Pattern.compile(dataPattern);

		//Match the given string with the pattern
		Matcher m = p.matcher(dataStr);

		//check whether match is found 
		boolean matchFound = m.matches();
		System.out.println("matchFound =["+matchFound+"]");
		return matchFound;
	}
}