/**
* PURPOSE : Validation & ItemChanged for Inventory lock
* AUTHOR : Changed By Sumit On 09/08/2011 [WM1ESUN001] 
*/ 

package ibase.webitm.ejb.wms;

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

import java.util.regex.*;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql. PreparedStatement;
import java.sql.ResultSet;
import org.w3c.dom.*;

@javax.ejb.Stateless
public class InvLockIC extends ValidatorEJB implements InvLockICRemote, InvLockICLocal
{
	/**
	* 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)
			{
				System.out.println ( "allXmlDataStr: " + allXmlDataStr);
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = wfValData( currDom, hdrDom, allDom, objContext, editFlag, xtraParams );
			System.out.println ( "ErrString: InvLockIC" + errString);
		}
		catch(Exception e)
		{
			System.out.println ( "Exception: InvLockIC: wfValData(String currXmlDataStr): " + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println ( "Returning from InvLockIC 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 = "";
		String errString = "";
		Connection connectionObject = null;		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
      	NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		String lockCode = null;
		String sql = null;
		String refSer = null;

        int count = 0;

        int ctr = 0;
		int noOfChilds = 0;
		int currentFormNo = 0;

		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			connectionObject = connDriver.getConnectDB("DriverValidator");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}

			System.out.println(" editFlag [" + editFlag + "] ");

			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);
				if( childNode.getNodeType() != Node.ELEMENT_NODE )
				{
					continue;
				}
				childNodeName = childNode.getNodeName();
				System.out.println(" columnName [" + childNodeName + "] ");
				switch(currentFormNo)
				{           
					case 1:
						if( childNodeName.equalsIgnoreCase("lock_code") && editFlag != null && editFlag.trim().equalsIgnoreCase("A") )
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("lock_code","NULLLOCKCD",userId);
								break;
							}
							else
							{
								lockCode = checkNull( genericUtility.getColumnValue("lock_code",currDom) );

								if ( lockCode.trim().indexOf(" ") > 0 )
								{
									errString = getErrorString("lock_code","INVLOCKCD",userId);
									break;
								}
								boolean isValid = isValidData(lockCode);
								if ( !isValid )
								{
									errString = getErrorString("lock_code","INVLOCKCD",userId);
									break;
								}

								sql = "SELECT COUNT(*) AS 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","INVLOCKEXT",userId);
									break;
								}
							}
						}
						else if(childNodeName.equalsIgnoreCase("descr"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("descr","NULLDESCR",userId);
								break;
							}
						}
					break;
					
					case 2:
						if(childNodeName.equalsIgnoreCase("lock_code"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("lock_code","NULLLOCKCD",userId);
								break;
							}
						}
						else if(childNodeName.equalsIgnoreCase("tran_ser"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("tran_ser","NULLREFSER",userId);
								break;
							}
							else
							{
								refSer = checkNull( genericUtility.getColumnValue("tran_ser",currDom) );
								sql = "SELECT COUNT(*) COUNT FROM REFSER WHERE REF_SER = ? ";
								pstmt = connectionObject.prepareStatement(sql);
								pstmt.setString(1, refSer );
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								if( count == 0 )
								{
									errString = getErrorString("tran_ser","INVREFSER",userId);
									break;
								}
								String refSerDet = "";
								int refSerCnt = 0;
								NodeList refSerList = allDom.getElementsByTagName("tran_ser");
								int noOfDetail = refSerList.getLength();
								System.out.println(" noOfDetail = [" + noOfDetail + "] ");
								for( int det = 0; det < noOfDetail ; det++ )
								{
									if ( refSerList.item( det ).getFirstChild() != null )
									{
										refSerDet = checkNull(( refSerList.item( det ).getFirstChild() ).getNodeValue());
									}
									System.out.println( " refSerDet = ["+refSerDet+"]" );
									if( refSerDet.trim().equals( refSer.trim() ) )
									{
										refSerCnt++;
									}
								}
								System.out.println(" refSerCnt = [" + refSerCnt + "] ");
								if ( refSerCnt > 1 )
								{
									errString = getErrorString("tran_ser","DUPREFSER",userId);
									break;
								}
							}
						}
						else if(childNodeName.equalsIgnoreCase("allow"))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("allow","NULLALLOW",userId);
								break;
							}
						}
					break;
						
				}//End Switch
				if ( errString != null && errString.trim().length() > 0 )
				{
					break;
				}
			}//End For
		}//End Try
		catch(Exception e)
		{
			System.out.println("Exception: InvLockIC: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}
		finally
		{
			try
			{
				if (connectionObject != null)
				{
					if (pstmt != null)
					{
						if (rs != null)
						{
							rs.close();
						}
						pstmt.close();
					}
					connectionObject.close();
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}// End Finally
		return (errString);
	}// END wfValData
	
	/**
	* 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 = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :InvLockIC :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from InvLockIC 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 itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String errString = "";
		String lockCode = "";
		int currentFormNo = 0;
		StringBuffer valueXmlString = new StringBuffer();
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
						
			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" );
			//coding of item default
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
				case 2:
					valueXmlString.append("<Detail2>\r\n");
					if ( currentColumn.trim().equalsIgnoreCase( "itm_default" ))
					{	
						lockCode = genericUtility.getColumnValue("lock_code",hdrDom);
						//To set default lock_code as entered in form 1
						valueXmlString.append( "<lock_code protect ='1'><![CDATA[" ).append( lockCode ).append( "]]></lock_code>\r\n" );
					}
					valueXmlString.append("</Detail2>\r\n");
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception: InvLockIC: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}
		valueXmlString.append( "</Root>\r\n" );	
		return (valueXmlString.toString());
	}// END itemChanged Method.
	
	
	//To check Null String
	private String checkNull(String input)
	{
		if (input==null)
		{
			input="";
		}
		return input;
	}
	/** 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;
	}
}
