package ibase.webitm.ejb.mfg;

import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ValidatorEJB;
//import ibase.webitm.ejb.bmr.util.TagIndex;
//import ibase.webitm.ejb.bmr.util.TagSpec;
//import ibase.webitm.ejb.bmr.util.Utils;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;
//import ibase.webitm.ejb.bmr.util.*;
import java.util.*;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.ejb.Stateless; // added for ejb3

@Stateless // added for ejb3


public class ProcRouteInstrIc extends ValidatorEJB implements ProcRouteInstrIcLocal,ProcRouteInstrIcRemote //SessionBean
{
	GenericUtility genericUtility = GenericUtility.getInstance(); 

	/*public void ejbCreate() throws RemoteException, CreateException 
	{
	}
	public void ejbRemove()
	{
	}
	public void ejbActivate() 
	{
	}
	public void ejbPassivate() 
	{
	}*/
	public String wfValData() throws RemoteException,ITMException
	{
		return "";
	}

	public String itemChanged() throws RemoteException,ITMException
	{
		return "";
	}
	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;
		System.out.println("xmlString........"+xmlString);
		System.out.println("xmlString1........"+xmlString1);
		System.out.println("xmlString2........"+xmlString2);
		try
		{
			dom = parseString(xmlString);
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
			}
			errString = wfValData(dom,dom1,dom2,objContext,editFlag,xtraParams);
		}
		catch(Exception 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
	{
		String errString = " ";
		String errCode = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		int ctr = 0;
		String startDate = null,endDate = null;
		String columnValue = null;
		String childNodeName = null;

		String userId = null,loginSite = null;
		String templateCode = "",descr = "" ,workCenter = "" , mcCode = "";


		int cnt = 0;
		int currentFormNo = 0;
		int childNodeListLength;
		Connection conn = null;
		PreparedStatement pStmt=null;
		ResultSet rs = null;
		String sql = null;
		ArrayList errList = new ArrayList();
		ArrayList errFields = new ArrayList();
		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>"); 
		String errorType = "";

		ConnDriver connDriver = new ConnDriver();
		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams,"loginCode");
			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");
			genericUtility = GenericUtility.getInstance(); 
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			switch(currentFormNo)
			{
			case 1 :
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for(ctr = 0; ctr < childNodeListLength; ctr++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if ( childNodeName.equals( "operation" ) )
					{
						String numValStr = null;
						int llCount = 0;
						numValStr = genericUtility.getColumnValue( "operation", dom );
						int llVal = Integer.parseInt( numValStr );
						String lsVal = genericUtility.getColumnValue( "route_code", dom );
						sql = " select count(1) cnt from procroute "
								+"	where route_code = ? "
								+"  	and operation = ? ";

						pStmt = conn.prepareStatement( sql );
						pStmt.setString( 1, lsVal );
						pStmt.setInt( 2, llVal );
						rs = pStmt.executeQuery();
						if( rs.next() )
						{ 
							llCount = rs.getInt( "cnt" );
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;

						if( llCount == 0 )
						{
							errCode = "VTINVOPR";//~t The entered Operation not exists in Process Route Master"
							//errString = getErrorString( "", errCode, userId );
							//break;
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
					}
					/*
						if ( childNodeName.equals( "take_observ" ) )
						{
							String lsVal =  genericUtility.getColumnValue( "take_observ", dom);
							if(  lsVal == null || lsVal.trim().length() == 0 )
							{
								errCode = "VTOBSYNBLK"; //~t Take Observation should be either Yes or No."
								errString = getErrorString( "", errCode, userId );
								break;
							}
						}
						if ( childNodeName.trim().equals( "no_of_observ" ) )
						{
							String lsVal = genericUtility.getColumnValue( "take_observ", dom );
							String noOfObserv = genericUtility.getColumnValue( "no_of_observ", dom );
							int llVal = Integer.parseInt( noOfObserv == null || noOfObserv.trim().length() == 0 ? "0" : noOfObserv.trim() );
							if( "Y".equalsIgnoreCase( lsVal ) && llVal == 0 )
							{
								errCode = "VMNOOBS";//~t Take Observation is Yes, No. of Observation should be more than zero"
								errString = getErrorString( "", errCode, userId );
								break;
							}
						}	

						if ( childNodeName.trim().equals( "trig_time" ) || childNodeName.trim().equals( "hours_after" ) )
						{
							String hoursAfter = genericUtility.getColumnValue( "hours_after", dom );
							int lcVal = Integer.parseInt( hoursAfter == null || hoursAfter.trim().length() == 0 ? "0" : hoursAfter.trim() );
							if( lcVal == 0 )
							{
								errCode = "VTINHRS";//~t Time Interval should not be zero"
							}
						}
					 */
					else  if ( childNodeName.equals( "template_code" ) )//aded by kunal
					{

						templateCode = checkNull(genericUtility.getColumnValue( "template_code", dom ));
						System.out.println("templateCode="+templateCode);
						if( templateCode == null || templateCode.trim().length() == 0 )
						{
							errCode = "VMTEMCD";
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{

							sql = " select count(*)  from bmr_template where template_code = ?  ";
							pStmt = conn.prepareStatement( sql );
							pStmt.setString( 1, templateCode );
							rs = pStmt.executeQuery();
							if( rs.next() )
							{ 
								cnt = rs.getInt(1 );
							}
							rs.close();
							rs = null;
							pStmt.close();
							pStmt = null;

							if( cnt == 0 )
							{
								errCode = "VMTEMCD1";
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
					}
					else  if ( childNodeName.equals( "descr" ) )//added by kunal 26/11/12
					{

						descr = checkNull(genericUtility.getColumnValue( "descr", dom ));
						System.out.println("Descr="+descr);
						if( descr == null || descr.trim().length() == 0 )
						{
							errCode = "VMDESCR";
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
					}
					/*if ( childNodeName.trim().equals( "template_no" ) ) //comment by Kunal on 23/11/12
						{
							String lsVal = genericUtility.getColumnValue( "template_no", dom );
							lsVal = lsVal != null ? lsVal.trim(): "";

							if( "012".indexOf( lsVal ) == -1 )
							{
								errCode = "VMINVTMPNO";//Invalid Template No or Blank.
								//errString = getErrorString( "", errCode, userId );
								//break;
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}

							//valid for tags
							String seqNo = null;//genericUtility.getColumnValue( childNodeName.trim(), dom );
							//String editFlg = getNodeValue( dom.getElementsByTagName("Detail2").item(0), "updateFlag", true );
							String instruction = genericUtility.getColumnValue( "instruction", dom );
							String observHead = null;//genericUtility.getColumnValue( "observ_head", dom );
							String observTrail = null;//genericUtility.getColumnValue( "observ_trail", dom );
							String defaultValue = null;//genericUtility.getColumnValue( "default_value", dom );

							//check for two tags cant have same ref
							ArrayList tagList = Utils.getAllCustomTagSpecs( instruction );
							int tagListLen = tagList.size();
							HashMap tagRefMap = new HashMap(); 

							for( int idx = 0; idx < tagListLen; idx++ )
							{

								if( tagRefMap.containsKey( "observ" + Utils.getTagAttrb( ( ( TagIndex )tagList.get( idx ) ).tagSpec , "ref" ) ) )
								{
									//errString = getErrorString( "instruction", "VMINVREFS", userId );
									errCode = "VMINVREFS";
									//return errString;
									errList.add( errCode );
									errFields.add( childNodeName.toLowerCase() );
								}
								else
								{
									String refStr = Utils.getTagAttrb( ((TagIndex)tagList.get( idx )).tagSpec , "ref" );
									//check for is no

									System.out.println( "refStr::" + refStr );
									if( refStr != null && refStr.trim().length() > 0 )
									{
										boolean isNumFlag = true;
										int refIntVal = -1;
										try
										{
											refIntVal = Integer.parseInt( refStr );
											if( refIntVal <= 0 )
											{
												isNumFlag = false;
											}
										}catch( Exception ex )
										{
											isNumFlag = false;
										}
										if( isNumFlag )
										{
											tagRefMap.put(  "observ" + refStr, ( (TagIndex)tagList.get( idx ) ).tagSpec );
										}
										else
										{
											//return getErrorString( "instruction", "VMINVREF", userId );
											errCode = "VMINVREF";
											errList.add( errCode );
											errFields.add( childNodeName.toLowerCase() );
										}
									}
								}
							}
							tagRefMap.clear();
							tagRefMap = null;
							//end check for two tags cant have same ref.

							HashMap tagMap = Utils.getAllTagsSeqNoMap( instruction );

							java.util.Set allTags = tagMap.entrySet();

							Iterator tagIter = allTags.iterator();

							while( tagIter.hasNext() )
							{
								Map.Entry mapObj = (Map.Entry)tagIter.next();

								seqNo = (String)mapObj.getKey();

								String tag = (String)mapObj.getValue();//(String)tagMap.get( "observ" + seqNo );
								TagSpec tagSpecObj = new TagSpec( tag );

								if( tagSpecObj.tagName.equalsIgnoreCase( "table" ) && tagSpecObj.defaultValue != null && tagSpecObj.defaultValue.trim().length() > 0 )
								{	
									errCode = Utils.isEntryValid( tag, tagSpecObj.observHead, null, tagSpecObj.defaultValue );
								}
								if( errCode != null && errCode.trim().length() > 0 )
								{
									//errString = getErrorString( "instruction", errCode, userId );
									//return errString;
									errCode = "VMINVREF";
									errList.add( errCode );
									errFields.add( childNodeName.toLowerCase() );
								}
								if( tagSpecObj.tagName.equalsIgnoreCase( "input" ) && tag.indexOf( "size={" ) > -1 )
								{
									//errString = getErrorString( "instruction", "VMINVSZATR", userId );
									errCode = "VMINVSZATR";
									errList.add( errCode );
									errFields.add( childNodeName.toLowerCase() );
								}
							}
							//end validation for tags
						}*/
					if ( childNodeName.trim().equals( "route_code" ) )
					{
						int count = 0;
						String lsVal = genericUtility.getColumnValue( "route_code", dom );
						lsVal = lsVal != null ? lsVal.trim(): "";

						sql = " select count(1) cnt from route where ROUTE_CODE = ? ";

						pStmt = conn.prepareStatement( sql );
						pStmt.setString( 1, lsVal );
						rs = pStmt.executeQuery();
						if( rs.next() )
						{
							count = rs.getInt( "cnt" );
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;

						if( count == 0 )
						{
							errCode = "VMINVROUTE";//Invalid Route or Blank.
							//errString = getErrorString( "", errCode, userId );
							//break;
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
					}
					else  if ( childNodeName.equals( "work_ctr" ) )// aaded by kunal on 05/DEC/13
					{
						workCenter = checkNull(genericUtility.getColumnValue( "work_ctr", dom ));
						System.out.println("work_ctr="+workCenter);
						if( workCenter == null || workCenter.trim().length() == 0 )
						{
							errCode = "VEWCTR1   ";
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = " select count (*)  from workcntr where work_ctr =  ?   ";
							pStmt = conn.prepareStatement( sql );
							pStmt.setString( 1, workCenter );
							rs = pStmt.executeQuery();
							if( rs.next() )
							{ 
								cnt = rs.getInt(1 );
							}
							rs.close();
							rs = null;
							pStmt.close();
							pStmt = null;
							if(cnt == 0)
							{
								errCode = "VTWCTR1   ";
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
					}
					else  if ( childNodeName.equals( "mc_code" ) )// aaded by kunal on 05/DEC/13
					{
						mcCode = checkNull(genericUtility.getColumnValue( "mc_code", dom ));
						System.out.println("mcCode="+mcCode);
						if( mcCode == null || mcCode.trim().length() == 0 )
						{
							errCode = "VMMACH01";
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = " select count (*) from machines where mc_code =  ?   ";
							pStmt = conn.prepareStatement( sql );
							pStmt.setString( 1, mcCode );
							rs = pStmt.executeQuery();
							if( rs.next() )
							{ 
								cnt = rs.getInt(1 );
							}
							rs.close();
							rs = null;
							pStmt.close();
							pStmt = null;
							if(cnt == 0)
							{
								errCode = "VMMACH00  ";
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
					}
					else  if ( childNodeName.equals( "work_ctr__alt" ) )// aaded by kunal on 05/DEC/13
					{
						workCenter = checkNull(genericUtility.getColumnValue( "work_ctr__alt", dom ));
						System.out.println("work_ctr="+workCenter);
						if( workCenter != null && workCenter.trim().length() > 0 )
						{
							sql = " select count (*)  from workcntr where work_ctr =  ?   ";
							pStmt = conn.prepareStatement( sql );
							pStmt.setString( 1, workCenter );
							rs = pStmt.executeQuery();
							if( rs.next() )
							{ 
								cnt = rs.getInt(1 );
							}
							rs.close();
							rs = null;
							pStmt.close();
							pStmt = null;
							if(cnt == 0)
							{
								errCode = "VTWCTR1   ";
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
					}
					else  if ( childNodeName.equals( "mc_code__alt" ) )// aaded by kunal on 05/DEC/13
					{
						mcCode = checkNull(genericUtility.getColumnValue( "mc_code__alt", dom ));
						System.out.println("mcCode="+mcCode);
						if( mcCode != null && mcCode.trim().length() >  0 )
						{
							sql = " select count (*) from machines where mc_code =  ?   ";
							pStmt = conn.prepareStatement( sql );
							pStmt.setString( 1, mcCode );
							rs = pStmt.executeQuery();
							if( rs.next() )
							{ 
								cnt = rs.getInt(1 );
							}
							rs.close();
							rs = null;
							pStmt.close();
							pStmt = null;
							if(cnt == 0)
							{
								errCode = "VMMACH00  ";
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
						
					}
					
				}
				break;
			case 2 :
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				for(ctr = 0; ctr < childNodeListLength; ctr++)
				{
					cnt = 0;
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					/*
						if ( childNodeName.trim().equals( "observ_type" ) )
						{
							String lsVal = genericUtility.getColumnValue( childNodeName.trim(), dom ); //dw_detedit[ii_currformno].getitemstring(1,ls_fldname)
							if( lsVal == null || lsVal.trim().length() == 0 )
							{
								errCode = "VMINVTYP";//~t Observation Type cannot be empty"
								errString = getErrorString( "", errCode, userId );
								break;
							}
						}	
						if ( childNodeName.trim().equals( "mandatory" ) )
						{
							String lsVal = genericUtility.getColumnValue( childNodeName.trim(), dom );//dw_detedit[ii_currformno].getitemstring(1,ls_fldname)
							if( lsVal == null || lsVal.trim().length() == 0 )
							{
								errCode = "VMMANDA";//~t Mandatory Field cannot be empty"
								errString = getErrorString( "", errCode, userId );
								break;
							}
						}
					 
					if ( childNodeName.trim().equals( "seq_no" ) )
					{
						String seqNo = genericUtility.getColumnValue( childNodeName.trim(), dom );
						String editFlg = getNodeValue( dom.getElementsByTagName("Detail2").item(0), "updateFlag", true );
						String instruction = genericUtility.getColumnValue( "instruction", dom1 );
						String observHead = genericUtility.getColumnValue( "observ_head", dom );
						String observTrail = genericUtility.getColumnValue( "observ_trail", dom );
						String defaultValue = genericUtility.getColumnValue( "default_value", dom );

						HashMap tagMap = Utils.getAllTagsSeqNoMap( instruction );

						if( ( !"D".equalsIgnoreCase( editFlg ) ) && !tagMap.containsKey( "observ" + seqNo ) )
						{
							//sequence no not refered in instruction.
							errCode = "VMINVSEQ";
							//errString = getErrorString( "", errCode, userId );
							//break;
							errList.add( errCode );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							String tag = (String)tagMap.get( "observ" + seqNo ); 
							errCode = Utils.isEntryValid( tag, observHead, observTrail, defaultValue );
							if( errCode != null && errCode.trim().length() > 0 )
							{
								//errString = getErrorString( "", errCode, userId );
								//break;
								errList.add( errCode );
								errFields.add( childNodeName.toLowerCase() );

							}else
							{
								//map of tags with ref, and it is not table then keep default and header fields disabled.
								if( tagMap.containsKey( "observ" + seqNo ) )
								{
									String tagSpec = (String) tagMap.get( "observ" + seqNo );
									TagSpec tagSpecObj = new TagSpec( tagSpec );
									if( tagSpecObj.tagName.indexOf( "table" ) == - 1 )
									{
										if( ( observHead != null && observHead.trim().length() > 0 ) )
										{
											errCode = "VMINVHEAD";
											//errString = getErrorString( "", errCode, userId );
											//break;												
											errList.add( errCode );
											errFields.add( childNodeName.toLowerCase() );
										}
										if( defaultValue != null && defaultValue.trim().length() > 0 )
										{
											errCode = "VMINVDFLT";
											//errString = getErrorString( "", errCode, userId );
											//break;
											errList.add( errCode );
											errFields.add( childNodeName.toLowerCase() );
										}
									}
								}
								//end map of tags with ref, and it is not table then keep default and header fields disabled.
							}
						}
					}
						*/
				}//END FOR OF CASE2
				break;
			}//END SWITCH
			int errListSize = errList.size();
			cnt =0;
			String errFldName = null;
			if ( errList != null && errListSize > 0 )
			{
				for (cnt = 0; cnt < errListSize; cnt++ )
				{
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					System.out.println("errCode .........."+errCode);
					//String errMsg = hashMap.get(errCode)!=null ? hashMap.get(errCode).toString():"";
					//System.out.println("errMsg .........."+errMsg);
					errString = getErrorString( errFldName, errCode, userId );
					errorType =  errorType( conn , errCode );
					if ( errString.length() > 0)
					{
						String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
						bifurErrString =bifurErrString;//+"<trace>"+errMsg+"</trace>";
						bifurErrString =bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						System.out.println("errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;

				errStringXml.append("</Errors></Root>\r\n");
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
		}//END TRY
		catch(Exception e)
		{
			e.printStackTrace();
			errCode = "VALEXCEP";
			errString = getErrorString( "", errCode, userId );									
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if( pStmt != null )
					{
						pStmt.close();
						pStmt = null;
					}

					if( rs != null )
					{
						rs.close();
						rs = null;
					}
					conn.close();
				}
				conn = null;
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
		}
		return errString;
	}//END OF VALIDATION 

	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 =   ? ";
			if (errorCode ==  null)
			{
				errorCode = "";
			}
			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;
	}


	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 valueXmlString = null;
		try
		{
			dom = parseString(xmlString); 
			dom1 = parseString(xmlString1); 
			if (xmlString2.trim().length() > 0 )
			{
				dom2 = parseString("<Root>" + xmlString2+ "</Root>");
			}
			valueXmlString = itemChanged(dom,dom1,dom2,objContext,currentColumn,editFlag,xtraParams);
		}
		catch(Exception e)
		{
			e.printStackTrace();
			throw new ITMException( e );
		}
		return valueXmlString; 
	}

	public String itemChanged(Document dom, Document dom1,Document dom2, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Connection conn = null;
		ConnDriver connDriver = new ConnDriver();
		PreparedStatement pStmt = null;
		ResultSet rs = null;
		String sql = null;
		int currentFormNo = 0;
		StringBuffer valueXmlString = new StringBuffer();
		String columnValue = null;

		NodeList parentNodeList = null;
		Node parentNode = null; 
		Node childNode = null;
		NodeList childNodeList = null;
		String childNodeName = null;
		int childNodeListLength = 0;
		int ctr = 0;

		String  loginSite = null; 

		try
		{
			conn = connDriver.getConnectDB("DriverITM");
			connDriver = null;
			if(objContext != null && objContext.trim().length()>0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}

			loginSite = getValueFromXTRA_PARAMS(xtraParams, "loginSiteCode");

			valueXmlString = new StringBuffer("<?xml version=\"1.0\"?><Root><header><editFlag>");
			valueXmlString.append(editFlag).append("</editFlag></header>");

			switch (currentFormNo)
			{
			case 1:
				valueXmlString.append("<Detail1>");	
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0;
				childNodeListLength = childNodeList.getLength();
				do
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equals(currentColumn))
					{
						if (childNode.getFirstChild() != null)
						{
							columnValue=childNode.getFirstChild().getNodeValue().trim();
						}
					}
					ctr++;
				}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));

				if ( currentColumn.trim().equals( "itm_defaultedit" ) )
				{
					/*
						String takeObserv = genericUtility.getColumnValue( "take_observ", dom );
						if( columnValue != null && "N".equalsIgnoreCase( columnValue.trim() ) )
						{						
							valueXmlString.append("<no_of_observ protect=\"1\">").append("<![CDATA[]]>").append("</no_of_observ>");
						}
					 */

					/*String templatenoDescr = null;
					String templateNo = genericUtility.getColumnValue( "template_no", dom );
					
					if( templateNo != null )
					{
						sql = " select descr from gencodes where fld_name = 'TEMPLATE_NO' and mod_name = 'W_PROCROUTE_INSTR' and fld_value = ? ";

						pStmt = conn.prepareStatement( sql );
						pStmt.setString(1, templateNo.trim() );
						rs = pStmt.executeQuery();
						if( rs.next() )
						{ 
							templatenoDescr = rs.getString( "DESCR" );
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;
					}
					valueXmlString.append("<templateno_descr>").append("<![CDATA[" + ( templatenoDescr != null ? templatenoDescr.trim() : "" )+ "]]>").append("</templateno_descr>");*/
				}
				/*
					if ( currentColumn.trim().equals( "take_observ" ) )
					{
						String description = null;
						if( columnValue != null && "N".equalsIgnoreCase( columnValue.trim() ) )
						{
							valueXmlString.append("<no_of_observ protect=\"1\">").append("<![CDATA[]]>").append("</no_of_observ>");							          
						}
					}
				 */	
				if ( currentColumn.trim().equals( "route_code" ) )
				{
					String description = null;
					if( columnValue != null )
					{

						sql = " select DESCR from route where ROUTE_CODE = ? ";

						pStmt = conn.prepareStatement( sql );
						pStmt.setString( 1, columnValue );
						rs = pStmt.executeQuery();
						if( rs.next() )
						{
							description = rs.getString( "DESCR" );
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;
					}
					valueXmlString.append("<route_descr>").append("<![CDATA[" + ( description != null ? description.trim() : "" )+ "]]>").append("</route_descr>");
				}	
				if ( currentColumn.trim().equals( "item_code" ) )
				{
					String itemcode = null;
					if( columnValue != null )
					{
						sql = " select DESCR from item where item_code = ? ";

						pStmt = conn.prepareStatement( sql );
						pStmt.setString(1,columnValue );
						rs = pStmt.executeQuery();
						if( rs.next() )
						{ 
							itemcode = rs.getString( "DESCR" );
						}
						rs.close();
						rs = null;
						pStmt.close();
						pStmt = null;
					}
					valueXmlString.append("<item_descr>").append("<![CDATA[" + ( itemcode != null ? itemcode.trim() : "" )+ "]]>").append("</item_descr>");
				}
				if( currentColumn.trim().equals( "operation" ) )
				{
					int nextSeqNo = 0;
					String oprStr =  genericUtility.getColumnValue( "operation", dom );
					String routeCd = genericUtility.getColumnValue( "route_code", dom );
					String workCenter = "",mcCode = "" ;

					int operationVal = Integer.parseInt( oprStr != null && !"null".equals( oprStr ) && oprStr.trim().length() > 0 ? oprStr.trim() : "0" );

					sql = " select nvl(max(nvl( seq_no, 0 )) + 1, 1) next_seq "
							+"	from procroute_oper_instr "
							+" where route_code = ? "
							+"	and operation = ? ";
					pStmt = conn.prepareStatement( sql );
					pStmt.setString( 1, routeCd );
					pStmt.setInt( 2, operationVal );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{ 
						nextSeqNo = rs.getInt( "next_seq" );
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;
					
					sql = "select work_ctr,mc_code from procroute where route_code  =  ? and operation = ?   ";
					pStmt = conn.prepareStatement( sql );
					pStmt.setString( 1, routeCd );
					pStmt.setInt( 2, operationVal );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{ 
						workCenter = checkNull(rs.getString( "work_ctr" ));
						mcCode = checkNull(rs.getString( "mc_code" ));
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;
					
					valueXmlString.append("<seq_no>").append("<![CDATA[" + ( nextSeqNo )+ "]]>").append("</seq_no>");
					valueXmlString.append("<work_ctr>").append("<![CDATA[" + workCenter+ "]]>").append("</work_ctr>");
					valueXmlString.append("<mc_code>").append("<![CDATA[" + mcCode+ "]]>").append("</mc_code>");
				}
				if ( currentColumn.trim().equals( "template_code" ) ) //change done by kunal on 23/11/12
				{
					String templatenoDescr = "",templateName = "";
					String templateCode = genericUtility.getColumnValue( "template_code", dom );
					
					sql = " select descr ,template_name from bmr_template  where template_code = ? ";
					pStmt = conn.prepareStatement( sql );
					pStmt.setString(1, templateCode );
					rs = pStmt.executeQuery();
					if( rs.next() )
					{ 
						templatenoDescr = rs.getString( "descr" );
						templateName = rs.getString( "template_name" );
					}
					rs.close();
					rs = null;
					pStmt.close();
					pStmt = null;

					valueXmlString.append("<bmr_template_descr>").append("<![CDATA[" + templatenoDescr + "]]>").append("</bmr_template_descr>");
					valueXmlString.append("<template_name>").append("<![CDATA[" + templateName + "]]>").append("</template_name>");//added by kunal on 27/AUG/13
				}

				valueXmlString.append("</Detail1>");
				valueXmlString.append("</Root>");	
				break;
			case 2:
				valueXmlString.append("<Detail2>");	
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				ctr = 0;
				childNodeListLength = childNodeList.getLength();
				do
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					if(childNodeName.equals(currentColumn))
					{
						if (childNode.getFirstChild() != null)
						{
							columnValue=childNode.getFirstChild().getNodeValue().trim();
						}
					}
					ctr++;
				}while(ctr < childNodeListLength  && !childNodeName.equals(currentColumn));

				if (currentColumn.trim().equals( "itm_default" ))
				{
					String seqNoStr = genericUtility.getColumnValue( "seq_no", dom1 );
					String oprStr =  genericUtility.getColumnValue( "operation", dom1 );
					String routeCd = genericUtility.getColumnValue( "route_code", dom1 );

					String nextSeqNoStr = Integer.toString( getNextSeqNo( dom2 ) );
					valueXmlString.append("<seq_no__instr>").append("<![CDATA[" + seqNoStr.trim() + "]]>").append("</seq_no__instr>");
					valueXmlString.append("<seq_no>").append("<![CDATA[" + nextSeqNoStr + "]]>").append("</seq_no>");

					//map of tags with ref, and it is not table then keep default and header fields disabled.
					String editFlg = getNodeValue( dom.getElementsByTagName("Detail2").item(0), "updateFlag", true );
					String instruction = genericUtility.getColumnValue( "instruction", dom1 );

					/*HashMap tagMap = Utils.getAllTagsSeqNoMap( instruction );
					//System.out.println( "nextSeqNoStr::" + nextSeqNoStr );
					if( tagMap.containsKey( "observ" + nextSeqNoStr ) )
					{
						String tagSpec = (String) tagMap.get( "observ" + nextSeqNoStr );
						//System.out.println( "tagSpec::" + tagSpec );
						TagSpec tagSpecObj = new TagSpec( tagSpec );
						if( tagSpecObj.tagName.indexOf( "table" ) == - 1 )
						{
							valueXmlString.append("<observ_head protect=\"1\">").append("<![CDATA[]]>").append("</observ_head>");
							valueXmlString.append("<default_value protect=\"1\">").append("<![CDATA[]]>").append("</default_value>");								
						}
						else
						{
							valueXmlString.append("<observ_head protect=\"0\">").append("<![CDATA[]]>").append("</observ_head>");
							valueXmlString.append("<default_value protect=\"0\">").append("<![CDATA[]]>").append("</default_value>");																
						}
					}*/

					//end map of tags with ref, and it is not table then keep default and header fields disabled.
				}
				valueXmlString.append("</Detail2>");					
				valueXmlString.append("</Root>");					
			}//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 e )
			{
				e.printStackTrace();
				throw new ITMException( e );
			}			
		}
		return valueXmlString.toString();
	}//END OF ITEMCHANGE	
	private String getCurrdateAppFormat()
	{
		String s = "";
		GenericUtility genericUtility = GenericUtility.getInstance();
		try
		{
			java.util.Date date = null;
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			System.out.println(genericUtility.getDBDateFormat());

			SimpleDateFormat simpledateformat = new SimpleDateFormat(genericUtility.getDBDateFormat());
			date = simpledateformat.parse(timestamp.toString());
			timestamp = Timestamp.valueOf(simpledateformat.format(date).toString() + " 00:00:00.0");
			s = (new SimpleDateFormat(genericUtility.getApplDateFormat())).format(timestamp).toString();
		}
		catch(Exception exception)
		{
			System.out.println("Exception in  getCurrdateAppFormat " + exception.getMessage());
		}
		return s;
	}
	private int getNextSeqNo( Document dom2 )
	{
		NodeList det2 = dom2.getElementsByTagName( "seq_no" );
		NodeList allDtl = dom2.getElementsByTagName( "Detail2" );
		int nextSeqNo = 0;
		//int det2Len = allDtl.getLength(); //det2.getLength();
		int det2Len = det2.getLength();
		Node seqNode = null;
		String seqStr = null;
		String editFlag = null;
		for( int idx = 1; idx < det2Len - 1; idx++ )
		{
			//seqNode = allDtl.item( idx );//det2.item( idx );
			seqNode = det2.item( idx );
			//editFlag = getNodeValue( seqNode, "updateFlag", true );
			//seqStr = getNodeValue( seqNode, "updateFlag", true );
			seqNode.getChildNodes().item(0).getNodeValue();
			//editFlag = allDtl.item( idx ).getAttributes().getNamedItem( "updateFlag" ).getNodeValue();

			//if( !"D".equalsIgnoreCase( editFlag ) )
			//{
			//seqStr = getNodeValue( seqNode, "seq_no", false );
			seqStr = seqNode.getChildNodes().item(0).getNodeValue();
			int seqNo = Integer.parseInt( seqStr );

			if( seqNo > nextSeqNo )
			{
				nextSeqNo = seqNo;
			}
			//}
		}
		return nextSeqNo + 1;
	}
	private String getNodeValue( Node currDet, String fldName, boolean isAttribute )
	{
		String fldValue = null;
		boolean isFound = false;
		NodeList currNodes = currDet.getChildNodes();
		int currDetLen = currNodes.getLength();
		for(int detIdx = 0; detIdx < currDetLen && !isFound ; detIdx++ )
		{
			Node currNode = currNodes.item( detIdx );
			String nodeName = currNode.getNodeName();

			if( isAttribute == true )
			{
				if ( nodeName.equalsIgnoreCase( "attribute" ) )
				{
					fldValue = currNode.getAttributes().getNamedItem( fldName ).getNodeValue();
					isFound = true;
				}				
			}
			else if ( currNode.getNodeType() == Node.ELEMENT_NODE && nodeName.equalsIgnoreCase( fldName ) )
			{
				fldValue = currNode.getFirstChild() != null ? currNode.getFirstChild().getNodeValue().trim() : null;
				isFound = true;
			}
		}
		return fldValue;
	}

	private String getAttrubute( Node attrNode, String attrName )
	{
		String attrVal = null;


		return attrVal;
	}
	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
}
