

/********************************************************
	Title     : WOTrackUpdateIC.java(M14BSUN003)
	Date      : 12-june-2014
	Developer : Kunal Mandhre
	Purpose   : Update the activities for Workorder, validation and itemchange 
********************************************************/

package ibase.webitm.ejb.sys;
import ibase.system.config.ConnDriver;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.ValidatorEJB;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

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

import javax.ejb.Stateless;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@Stateless  
public class WOTrackUpdateIC extends ValidatorEJB implements WOTrackUpdateICLocal,WOTrackUpdateICRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	public String wfValData(String xmlString, String xmlString1,  String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		try
		{
			
			if (xmlString != null && xmlString.trim().length() > 0 )
			{
				dom = parseString(xmlString);
				System.out.println("In wfValData Current xmlString="+xmlString);
			}
			if (xmlString1 != null && xmlString1.trim().length() > 0 )
			{
				dom1 = parseString(xmlString1);
				System.out.println("In wfValData Header xmlString1="+xmlString1);
			}
			
			errString = wfValData(dom, dom1,  objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document curDom, Document hdrDom, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
	 	String userId = "";
		String errorType = "";
		String childNodeName = null;
		String errCode = "";
		String actCode = "";
		String errString = "";
		String workorder = "",descr = "",refId = "",sql = "";
		int currentFormNo = 0;
		int childNodeListLength;
		int ctr=0;
		int cnt = 0 ,lineNo = 0;
		
		NodeList parentNodeList = null;
		NodeList childNodeList = null;	
		Node parentNode = null;
		Node childNode = null;
	
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		
		Connection conn = null;
		PreparedStatement pstmt = null ;
		ResultSet rs = null;
		ConnDriver connDriver = new ConnDriver();
	
		StringBuffer errStringXml = new StringBuffer("<?xml version = \"1.0\"?> \r\n <Root> <Errors>"); 
		
		try
		{
			
			//SimpleDateFormat sdf =  new SimpleDateFormat(genericUtility.getApplDateFormat());
			conn = connDriver.getConnectDB("DriverITM");
			userId = getValueFromXTRA_PARAMS(xtraParams, "loginCode");
			
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
			
			System.out.println("Current Form No. :- "+currentFormNo);
				
			switch(currentFormNo)
			{
			case 1 :
				parentNodeList = curDom.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.equalsIgnoreCase("tran_date")  ) 
					{
						if(genericUtility.getColumnValue("tran_date", curDom) == null)
						{
							errCode = "VTTRDT01";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					/*else if(childNodeName.equalsIgnoreCase("work_order")) 
					{
						workorder = checkNull(genericUtility.getColumnValue("work_order", curDom));
						
						if(workorder == null || workorder.trim().length() == 0)
						{
							errCode = "VTBLKTRRES1";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}else
						{
						
							if (!(isExist(conn, "workorder", "work_order", workorder)))
							{
								errCode = "VTBLKTRRES2";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							else  if (!(isExist(conn, "WO_TRACK_STATUS", "REF_ID", workorder)))
							{
								errCode = "VTBLKTRRES3";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						
					}*/
					else if(childNodeName.equalsIgnoreCase("ref_line_no")  ) 
					{
						
						lineNo = Integer.parseInt( checkNull(genericUtility.getColumnValue("ref_line_no", curDom)).trim().length() ==0 ?"0":checkNull(genericUtility.getColumnValue("ref_line_no", curDom)).trim() );
						refId = checkNull(genericUtility.getColumnValue("ref_id", curDom));
						if(lineNo == 0 )
						{
							errCode = "VTREFLN01";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							sql = "select count (*) from wo_track_status where tran_id = ? and line_no = ? ";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, refId );
							pstmt.setInt( 2, lineNo );
							rs = pstmt.executeQuery();
							if( rs.next() )
							{
								cnt = rs.getInt( 1 );
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							if(cnt == 0)
							{
								errCode = "VTREFLN02";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					}
					if(childNodeName.equalsIgnoreCase("event_date")  ) 
					{
						if(genericUtility.getColumnValue("event_date", curDom) == null)
						{
							errCode = "VTEVEDT01";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					else if(childNodeName.equalsIgnoreCase("descr")) 
					{
						descr = checkNull(genericUtility.getColumnValue("descr", curDom));
						if(descr == null || descr.trim().length() == 0)
						{
							errCode = "VMDESCR";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					}
					
				
				}
				 break;
			
				
				
			}
			int errListSize = errList.size();
			cnt = 0;
			String errFldName = null;
			if(errList != null && errListSize > 0)
			{
				for(cnt = 0; cnt < errListSize; cnt ++)
				{
					errCode = errList.get(cnt);
					errFldName = errFields.get(cnt);
					System.out.println("errCode .........." + errCode);
					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 + errString.substring(errString.indexOf("</trace>") + 8, errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						errString = "";
					}
					if(errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;
				errStringXml.append("</Errors> </Root> \r\n");
			}
			else
			{
				errStringXml = new StringBuffer("");
			}
		}//end try
		catch(Exception e)
		{
			e.printStackTrace();
			errString = e.getMessage();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if(conn != null)
				{
					if(rs != null) 
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null) 
					{
						pstmt.close();
						pstmt = null;
					}
					conn.close();
				}
				conn = null;
			} 
			catch(Exception d)
			{
				d.printStackTrace();
				throw new ITMException(d);
			}
		}
		errString = errStringXml.toString();
		return errString;
	}

	public String itemChanged(String xmlString, String xmlString1, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		String valueXmlString = "";
		try
		{   

			System.out.println("xmlString1="+xmlString);
			System.out.println("xmlString2="+xmlString1);
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			
			valueXmlString = itemChanged(dom, dom1,objContext, currentColumn, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			System.out.println("Exception : [DistributionRoute][itemChanged( String, String )] :==>\n" + e.getMessage());
		}
		return valueXmlString;
	}

	public String itemChanged(Document dom, Document dom1,String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		String childNodeName = null;
		String sql = "";
		String workorder = "",refId = "",actCode= "",eventNo="";
		String tranId = "",status = "",descr = "",remarks = "" ;
		StringBuffer valueXmlString = new StringBuffer();
		int lineNo = 0,count = 0;
		int ctr = 0;
		int currentFormNo = 0;
		int childNodeListLength = 0;
		Date tranDate = null,eventDate = null,completionDate = null;
		NodeList parentNodeList = null;
		NodeList childNodeList = null;
		Node parentNode = null;
		Node childNode = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null ;
		GenericUtility genericUtility = GenericUtility.getInstance();
		ConnDriver connDriver = new ConnDriver();
		java.sql.Timestamp currDate = null;
		String currDateStr = null;
		
		try
		{   
		
			currDate = new java.sql.Timestamp(System.currentTimeMillis());
			SimpleDateFormat sdf =  new SimpleDateFormat(genericUtility.getApplDateFormat());

			conn = connDriver.getConnectDB("DriverITM");
			conn.setAutoCommit(false);
			connDriver = null;
			if(objContext != null && objContext.trim().length() > 0)
			{
				currentFormNo = Integer.parseInt(objContext);
			}
	
			valueXmlString = new StringBuffer("<?xml version = \"1.0\"?> <Root> <header> <editFlag>");
			valueXmlString.append(editFlag).append("</editFlag> </header>");
			switch(currentFormNo)
			{
			case 1 : 
				parentNodeList = dom.getElementsByTagName("Detail1");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail1>");
				childNodeListLength = childNodeList.getLength();
				do
				{   
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					ctr ++;
				}while(ctr < childNodeListLength  && ! childNodeName.equals(currentColumn));
				System.out.println("currentColumn = "+currentColumn);
				
				
			
				if(currentColumn.trim().equalsIgnoreCase("itm_default") )
				{
					valueXmlString.append("<tran_date>").append("<![CDATA[" + sdf.format(new Date()) + "]]>").append("</tran_date>");
					workorder = checkNull(genericUtility.getColumnValue("work_order", dom));
					sql = " select  tran_id from wo_track_status where ref_id = ?  and ref_ser = 'W-ORD '  ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,workorder);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						refId = rs.getString("tran_id");
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					currDate = new java.sql.Timestamp(System.currentTimeMillis());
					currDateStr = sdf.format(currDate);
					valueXmlString.append("<ref_id>").append("<![CDATA[" + refId +"]]>").append("</ref_id>\r\n");
					valueXmlString.append("<tran_date>").append("<![CDATA[" + currDateStr +"]]>").append("</tran_date>\r\n");
				}
				/*else if(currentColumn.trim().equalsIgnoreCase("work_order"))  
				{	
					workorder = checkNull(genericUtility.getColumnValue("work_order", dom));
					sql = " select  tran_id from wo_track_status where ref_id = ?  and ref_ser = 'W-ORD '  ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,workorder);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						refId = rs.getString("tran_id");
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					valueXmlString.append("<ref_id>").append("<![CDATA[" + refId +"]]>").append("</ref_id>\r\n"); 
				}*/
				else if(currentColumn.trim().equalsIgnoreCase("ref_line_no"))  
				{	
					lineNo = Integer.parseInt( checkNull(genericUtility.getColumnValue("ref_line_no", dom)).trim().length() ==0 ?"0":checkNull(genericUtility.getColumnValue("ref_line_no", dom)).trim() );
					refId = checkNull(genericUtility.getColumnValue("ref_id", dom));

					sql = " select count(*) from wo_track_update where ref_id = ?  and ref_line_no = ?   ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,refId);
					pstmt.setInt(2,lineNo);
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						count = rs.getInt(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
					if(count > 0)
					{
						sql = " select tran_id,tran_date,status_flag,event_no,descr,event_date,completion_date,remarks  from wo_track_update where ref_id = ?  and ref_line_no = ?    ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,refId);
						pstmt.setInt(2,lineNo);
						rs = pstmt.executeQuery();
						if(rs.next())
						{

							tranId = rs.getString("tran_id");
							tranDate = rs.getDate("tran_date");
							status = rs.getString("status_flag");
							actCode = rs.getString("event_no");
							descr = rs.getString("descr");
							eventDate = rs.getDate("event_date");
							completionDate = rs.getDate("completion_date");
							remarks = rs.getString("remarks");
							
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						remarks = remarks == null ? "" : remarks.trim();
						
						valueXmlString.append("<tran_id>").append("<![CDATA[" + tranId +"]]>").append("</tran_id>\r\n");
						valueXmlString.append("<tran_date>").append("<![CDATA[" + sdf.format(tranDate) + "]]>").append("</tran_date>");
						valueXmlString.append("<status_flag>").append("<![CDATA[" + status +"]]>").append("</status_flag>\r\n");
						valueXmlString.append("<event_no>").append("<![CDATA[" + actCode +"]]>").append("</event_no>\r\n");
						valueXmlString.append("<descr protect = \"1\">").append("<![CDATA[" + descr +"]]>").append("</descr>\r\n");
						if(completionDate != null)
						{
							valueXmlString.append("<completion_date>").append("<![CDATA[" + sdf.format(completionDate) + "]]>").append("</completion_date>");
						}
						else
						{
							valueXmlString.append("<completion_date></completion_date>");
						}
						if(eventDate != null)
						{
							valueXmlString.append("<event_date protect = \"1\">").append("<![CDATA[" + sdf.format(eventDate) + "]]>").append("</event_date>");
						}
						else
						{
							valueXmlString.append("<event_date protect = \"1\">").append("<![CDATA[]]>").append("</event_date>");
						}
						valueXmlString.append("<remarks>").append("<![CDATA[" + remarks +"]]>").append("</remarks>\r\n");
					}
					else
					{

						sql = " select  act_code,event_no,REMARKS,ADD_DATE from wo_track_status where tran_id = ?  and line_no = ?   ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,refId);
						pstmt.setInt(2,lineNo);
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							actCode = rs.getString("act_code");
							eventNo=rs.getString("event_no");//added by mahendra 15-NOV-14
							remarks=rs.getString("REMARKS");//added by mahendra 15-NOV-14
							eventDate=rs.getDate("ADD_DATE");//added by mahendra 15-NOV-14
							System.out.println("actCode@@@@@ :"+actCode);
							System.out.println("eventNo :"+eventNo);
							System.out.println("remarks :"+remarks);
							System.out.println("eventDate :"+eventDate);
							
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						
						actCode = actCode == null ? "" : actCode.trim();
						eventNo = eventNo == null ? "" : eventNo.trim();
						remarks = remarks == null ? "" : remarks.trim();
						
						valueXmlString.append("<event_no>").append("<![CDATA[" + eventNo +"]]>").append("</event_no>\r\n");
						valueXmlString.append("<tran_id>").append("<![CDATA[]]>").append("</tran_id>\r\n");
						valueXmlString.append("<tran_date>").append("<![CDATA[" + sdf.format(currDate) + "]]>").append("</tran_date>");
						valueXmlString.append("<status_flag>").append("<![CDATA[2]]>").append("</status_flag>\r\n");
						valueXmlString.append("<descr protect = \"1\">").append("<![CDATA["+remarks+"]]>").append("</descr>\r\n");
						valueXmlString.append("<completion_date></completion_date>");
						valueXmlString.append("<event_date protect = \"1\">").append("<![CDATA[" + sdf.format(eventDate) + "]]>").append("</event_date>");
						valueXmlString.append("<remarks>").append("<![CDATA[]]>").append("</remarks>\r\n");

					}
				}//end ref line no
				
				valueXmlString.append("</Detail1>");
				break;       
		
			}
			valueXmlString.append("</Root>");
			
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Exception ::"+ e.getMessage());
			throw new ITMException(e);
		}
		finally
		{
  
			try
			{
				if(conn != null)
				{
					if(rs != null) 
					{
						rs.close();
						rs = null;
					}
					if(pstmt != null) 
					{
						pstmt.close();
						pstmt = null;

					}
					conn.close();
				}
				conn = null;	
			}
			catch(Exception d)
			{
				d.printStackTrace();
			}			
		}
		return valueXmlString.toString();
	}
	private String checkNull(String input) 
	{
		if(input == null)
		{
			input = "";
		}
		return input;
	}

	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 = ?";
			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;
	}
	
	
	private boolean isExist(Connection conn, String tableName, String columnName, String value) throws ITMException, RemoteException
	{
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		boolean status = false;
		try
		{
			sql = "SELECT count(*) from " + tableName + " where " + columnName + "  = ? ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, value);
			rs = pstmt.executeQuery();

			if (rs.next())
			{
				if (rs.getBoolean(1))
				{
					status = true;
				}
			}
			rs.close();
			rs = null;
			pstmt.close();
			pstmt = null;
		} catch (Exception e)
		{
			System.out.println("Exception in isExist ");
			e.printStackTrace();
			throw new ITMException(e);
		}
		System.out.println("returning String from isExist ");
		return status;
	}
	
	

 
}	