
/**
* PURPOSE : Validation & ItemChanged for Despatch
* AUTHOR : Changed By Sumit On 28/11/2011 [WM1FSUN004] 
*/ 

package ibase.webitm.ejb.wms;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class DespatchIC extends ValidatorEJB implements DespatchICRemote, DespatchICLocal
{
	/**
	* 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)
			{
				allDom = genericUtility.parseString(allXmlDataStr); 
			}
			errString = wfValData( currDom, hdrDom, allDom, objContext, editFlag, xtraParams );
			System.out.println ( "ErrString: DespatchIC" + errString);
		}
		catch(Exception e)
		{
			System.out.println ( "Exception: DespatchIC: wfValData(String currXmlDataStr): " + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			e.printStackTrace();
		}
		System.out.println ( "Returning from DespatchIC 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 = "",errString= "";
		
		Connection conn = null;		
		PreparedStatement pstmt = null;
		ResultSet rs = null;
      	NodeList parentList = null;
		NodeList childList = null;
		Node parentNode = null;
		Node childNode = null;
		String childNodeName = null;
		String despId = "", tranCode = "";
		String sql = null;
		//String tranSer = "";
        int count = 0;
        int ctr = 0;
		int noOfChilds = 0;
		int currentFormNo = 0;
		
		GenericUtility genericUtility = GenericUtility.getInstance();
		
		try
		{
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			userId = genericUtility.getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			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);
				childNodeName = childNode.getNodeName();
				switch(currentFormNo)
				{           
					case 1:
						if("desp_id".equalsIgnoreCase(childNodeName))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("desp_id","NULLDESPCD",userId);
								break;
							}
							else
							{
								if(editFlag.equalsIgnoreCase("A"))
								{
									sql = "SELECT COUNT(*) AS COUNT FROM DESPATCH WHERE DESP_ID = ?";
									despId = checkNull( genericUtility.getColumnValue("desp_id",currDom) );
									pstmt = conn.prepareStatement(sql);
									pstmt.setString(1, despId.trim());
									rs = pstmt.executeQuery();
									if( rs.next() )
									{
										count = rs.getInt("COUNT");
									}
									if( count == 0 )
									{
										errString = getErrorString("desp_id","INVDESPEXT",userId);
										break;
									}
									if(rs != null )
									{
										rs.close();
										rs = null;
									}
									if(pstmt != null )
									{
										pstmt.close();
										pstmt = null;
									}
								}
							}
							
						}
						if("tran_code".equalsIgnoreCase(childNodeName))
						{
							if(childNode.getFirstChild() == null)				
							{
								errString = getErrorString("tran_code","NULLTRANCD",userId);
								break;
							}
							else
							{
								sql = "SELECT COUNT(*) AS COUNT FROM TRANSPORTER WHERE TRAN_CODE = ?";
								tranCode = checkNull( genericUtility.getColumnValue("tran_code",currDom) );
								pstmt = conn.prepareStatement(sql);
								pstmt.setString(1, tranCode.trim());
								rs = pstmt.executeQuery();
								if( rs.next() )
								{
									count = rs.getInt("COUNT");
								}
								if( count == 0 )
								{
									errString = getErrorString("desp_id","INVTRANEXT",userId);
									break;
								}
								if(rs != null )
								{
									rs.close();
									rs = null;
								}
								if(pstmt != null )
								{
									pstmt.close();
									pstmt = null;
								}
							}
						}
						
					break;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception: DespatchIC: wfValData(Document dom): " + e.getMessage() + ":");
			errString = genericUtility.createErrorString(e);
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if (pstmt != null)
					{
						if (rs != null)
						{
							rs.close();
						}
						pstmt.close();
					}
					conn.close();
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}// End Finally
		return (errString);
    }
	public String itemChanged() throws RemoteException, ITMException
	{
		return "";
	}
	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); 
			}
			errString = itemChanged( dom, dom1, dom2, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception :DespatchIC :itemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
		}
		System.out.println ( "returning from DespatchIC itemChanged" );
		return errString;
	}
	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String despId ="", tranCode = "";		
		String sql = "";
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1 = null;
		ResultSet rs = null, rs1  = null;
		
		StringBuffer valueXmlString = new StringBuffer();
		int currentFormNo = 0;
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			System.out.println("INSIDE TRY OF itemChanged() ");			
			despId = checkNull( genericUtility.getColumnValue("desp_id", hdrDom));
			System.out.println("desp id-->["+despId+"]");
			
			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverValidator");
			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>\r\n" );
					if( "tran_code".equalsIgnoreCase( currentColumn.trim()) )
					{
						
						tranCode = genericUtility.getColumnValue("tran_code",currDom);
						
						sql = "SELECT TM.TRANS_MODE AS TMODE,T.TRAN_NAME AS TNAME FROM TRANSPORTER_MODE TM,TRANSPORTER T WHERE T.TRAN_CODE = TM.TRAN_CODE AND T.TRAN_CODE  = ?";
						
						System.out.println("SQL ["+sql+"]");
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, tranCode);
						rs = pstmt.executeQuery();			
						System.out.println("Query Executed");
						if(rs.next())
						{
							valueXmlString.append( "<trans_mode><![CDATA[" ).append( checkNull( rs.getString("TMODE")) ).append( "]]></trans_mode>\r\n" );
							valueXmlString.append( "<sh_name><![CDATA[" ).append( checkNull( rs.getString("TNAME")) ).append( "]]></sh_name>\r\n" );
							System.out.println("------------------------APPENDING DESCRIPTION of tran mode-------------------");						
														
						}
						else
						{
							valueXmlString.append( "<trans_mode><![CDATA[" ).append( "" ).append( "]]></trans_mode>\r\n" );
							valueXmlString.append( "<sh_name><![CDATA[" ).append( "" ).append( "]]></sh_name>\r\n" );
							System.out.println("------------------------EMPTY DESCRIPTION-------------------");
						}
						if(pstmt !=null) 
						{
							pstmt.close();
							pstmt = null;
						}
						if(rs != null )
						{
							rs.close();
							rs = null;
						}
							
					}
					valueXmlString.append( "</Detail1>\r\n" );
				}
				break;								
			}
			valueXmlString.append( "</Root>\r\n" );	
			System.out.println( "\n****ValueXmlString :" + valueXmlString.toString() + ":********" );
		}
		catch(Exception e)
		{
			System.out.println("Exception: DespatchIC: itemchanged(Document dom): " + e.getMessage() + ":");
			e.printStackTrace();			
		}
		finally
		{
			try
			{
				if (conn != null)
				{
					if(pstmt1 != null)
					{
						if(rs1 !=null)
						{
							rs1.close();
							rs1 = null;
						}
						pstmt1.close();
						pstmt1 = null;
					}
					if (pstmt != null)
					{
						if (rs != null)
						{
							rs.close();
						}
						pstmt.close();
					}
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
			
		}// End Finally
		
		return valueXmlString.toString();
	}
	// to check null
	private String checkNull(String input)
	{
		if (input==null)
		{
			input="";
		}
		return input;
	}	

}
