

/********************************************************
	Title     : TrackActivityMaster.java
	Date      : 24-JAN-2014
	Developer : Manoj Sarode
	Purpose   : Define the activities for user for Tacking.
********************************************************/

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 TrackActivityMaster extends ValidatorEJB implements TrackActivityMasterLocal,TrackActivityMasterRemote
{
	GenericUtility genericUtility = GenericUtility.getInstance();
	ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
	
	public String wfValData(String xmlString, String xmlString1, String xmlString2, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		String errString = "";
		Document dom = null;
		Document dom1 = null;
		Document dom2 = 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);
			}
			if (xmlString2 != null && xmlString2.trim().length() > 0 )
			{
				dom2 = parseString(xmlString2);
				System.out.println("In wfValData All xmlString2="+xmlString2);
			}
			errString = wfValData(dom, dom1, dom2, objContext, editFlag, xtraParams);
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		return(errString);
	}
	public String wfValData(Document curDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
	 	String userId = "";
		String errorType = "";
		String childNodeName = null;
		String errCode = "";
		String actCode = "";
		String actShDescr = "";
		String actDescr = "";
		String roleCode = "";
		String trackType = "";
		String trackLevel = "";
		String trackResponse = "";
		String errString = "";
		
		int currentFormNo = 0;
		int childNodeListLength;
		int ctr=0;
		int count = 0;
		
		boolean flag = false;
		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("act_code") && editFlag.equalsIgnoreCase("A") )     // Validation for activity code 
					{
						actCode = checkNull(genericUtility.getColumnValue("act_code", curDom));
						if(actCode == null || actCode.trim().length() == 0)
						{
							errCode = "VTBLNKACTV";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							flag = isRecordExist(conn," TRAN_TRACK_ACTS "," WHERE ACT_CODE ='"+actCode.trim()+"' ");
							if(flag == true)
							{
								errCode = "VTACTCDEXT";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					}   //act_code end
					else if(childNodeName.equalsIgnoreCase("sh_descr")) // Validation for Activity Short Description 
					{
						actShDescr = checkNull(genericUtility.getColumnValue("sh_descr", curDom));
						
						if(actShDescr == null || actShDescr.trim().length() == 0)
						{
							errCode = "VTBLNKDSCR";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						
					} // End of sh_descr 
					else if(childNodeName.equalsIgnoreCase("descr")) // Validation for Activity Description 
					{
						actDescr = checkNull(genericUtility.getColumnValue("descr", curDom));
						
						if(actDescr == null || actDescr.trim().length() == 0)
						{
							errCode = "VTBLNKDSCR";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					} // End of descr 
					else if(childNodeName.equalsIgnoreCase("role_code")) // Validation for role_code
					{
						roleCode = checkNull(genericUtility.getColumnValue("role_code", curDom));
						
						if(roleCode == null || roleCode.trim().length() == 0)
						{
							errCode = "VTBLNKROLL";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							//flag = isRecordExist(conn," GENCODES "," WHERE FLD_NAME = 'ROLE_CODE' AND MOD_NAME='W_TRACK_ACTS' AND FLD_VALUE = '"+roleCode.trim()+"' ");
							flag = isRecordExist(conn," WF_ROLE_USERS WRF,WF_ROLE WR ","  WHERE WR.ROLE_CODE=WRF.ROLE_CODE AND WRF.ROLE_CODE = '"+roleCode.trim()+"' ");
							
							if(flag == false)
							{
								errCode = "VTINVDROLL";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						
					} // End of role_code 
					else if(childNodeName.equalsIgnoreCase("track_type")) // Validation for track_type
					{
						trackType = checkNull(genericUtility.getColumnValue("track_type", curDom));
						
						if(trackType == null || trackType.trim().length() == 0)
						{
							errCode = "VTBLKTRTYP";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}else
						{
							flag = isRecordExist(conn," GENCODES "," WHERE FLD_NAME = 'TRACK_TYPE' AND MOD_NAME='W_TRACK_ACTS' AND FLD_VALUE = '"+trackType.trim()+"' ");
							
							if(flag == false)
							{
								errCode = "VTINVTRTYP";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							
						}
					} // End of track_type 
					else if(childNodeName.equalsIgnoreCase("track_level")) // Validation for track_level
					{
						trackLevel = checkNull(genericUtility.getColumnValue("track_level", curDom));
						
						if(trackLevel == null || trackLevel.trim().length() == 0)
						{
							errCode = "VTBLKTRLVL";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}else
						{
							flag = isRecordExist(conn," GENCODES "," WHERE FLD_NAME = 'TRACK_LEVEL' AND MOD_NAME='W_TRACK_ACTS' AND FLD_VALUE = '"+trackLevel.trim()+"' ");
							
							if(flag == false)
							{
								errCode = "VTINVTRLVL";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							
						}
					} // End of track_level 
					else if(childNodeName.equalsIgnoreCase("track_response")) // Validation for track_level
					{
						trackResponse = checkNull(genericUtility.getColumnValue("track_response", curDom));
						
						if(trackResponse == null || trackResponse.trim().length() == 0)
						{
							errCode = "VTBLKTRRES";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}else
						{
							flag = isRecordExist(conn," GENCODES "," WHERE FLD_NAME = 'TRACK_RESPONSE' AND MOD_NAME='W_TRACK_ACTS' AND FLD_VALUE = '"+trackResponse.trim()+"' ");
							
							if(flag == false)
							{
								errCode = "VTINVTRRES";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							
						}
						
					} // End of track_level 
					/*else if(childNodeName.equalsIgnoreCase("exp_comp_days")) // Validation for track_level
					{
						actShDescr = checkNull(genericUtility.getColumnValue("exp_comp_days", curDom));
						
						if(actCode == null || actCode.trim().length() == 0)
						{
							errCode = "VTBLNKACTV";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						
					} // End of track_level 
					 */					
					
				
				}
				 break;
			
				
				
			}
			int errListSize = errList.size();
			count = 0;
			String errFldName = null;
			ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
			if(errList != null && errListSize > 0)
			{
				for(count = 0; count < errListSize; count ++)
				{
					errCode = errList.get(count);
					errFldName = errFields.get(count);
					System.out.println("errCode .........." + errCode);
				//	errString = getErrorString(errFldName, errCode, userId);
					errString = itmDBAccessEJB.getErrorString(errFldName, errCode, userId);
					System.out.println("errString........"+errString);
					
					errString = itmDBAccessEJB.getErrorString("", errCode, userId);
					System.out.println("errString........"+errString);
					
					errorType = errorType(conn , errCode);
					return errString;
					
				}
				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 xmlString2,String xmlString3, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document dom = null;
		Document dom1 = null;
		Document dom2 = null;
		Document dom3=null;
		
	    	
		String valueXmlString = "";
		try
		{   
			if(xmlString != null && xmlString.trim().length() > 0)
			{
				dom = parseString(xmlString);
			}
			if(xmlString1 != null && xmlString1.trim().length() > 0)
			{
				dom1 = parseString(xmlString1);
			}
			if(xmlString2 != null && xmlString2.trim().length() > 0)
			{
				dom2 = parseString(xmlString2);
			}
			if(xmlString3 != null && xmlString3.trim().length() > 0)
			{
				dom3 = parseString(xmlString3);
			}
			System.out.println("xmlString1="+xmlString);
			System.out.println("xmlString2="+xmlString1);
			System.out.println("xmlString3="+xmlString2);
			System.out.println("xmlString4="+xmlString3);
			valueXmlString = itemChanged(dom, dom1, dom2,dom3, 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, Document dom2, Document dom3, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		String childNodeName = null;
		String sql = "";
		String roleCode = "";
		String roleCodeDescr = "";
		String trackType = "";
		String trackTypeDescr = "";
		String trackLevel = "";
		String trackLevelDescr = "";
		String trackResponse = "";
		String trackResonseDescr = "";
		
		StringBuffer valueXmlString = new StringBuffer();
		int ctr = 0;
		int currentFormNo = 0;
		int childNodeListLength = 0;
		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();
		try
		{   
			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("<emp_code__hod>").append("<![CDATA[I99993]]>").append("</emp_code__hod>\r\n");*/
					valueXmlString.append("<track_level>").append("<![CDATA[B]]>").append("</track_level>\r\n");
					
					sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_LEVEL' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ?";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,"B");
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						trackLevelDescr = rs.getString(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
                    valueXmlString.append("<track_level_descr>").append("<![CDATA[" + trackLevelDescr +"]]>").append("</track_level_descr>\r\n");
                    trackLevelDescr="";
                    
                    valueXmlString.append("<track_type>").append("<![CDATA[POS]]>").append("</track_type>\r\n");
                    
                    sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_TYPE' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ? ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,"POS");
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						trackTypeDescr = rs.getString(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
                    valueXmlString.append("<track_type_descr>").append("<![CDATA[" + trackTypeDescr +"]]>").append("</track_type_descr>\r\n"); 
                    trackTypeDescr="";
                    
                    valueXmlString.append("<track_response>").append("<![CDATA[D]]>").append("</track_response>\r\n");
					
                    sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_RESPONSE' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ? ";
					pstmt =  conn.prepareStatement(sql);
					pstmt.setString(1,"D");
					rs = pstmt.executeQuery();
					if(rs.next())
					{
						trackResonseDescr = rs.getString(1);
					}
					rs.close();
					rs = null;
					pstmt.close();
					pstmt = null;
                    valueXmlString.append("<track_response_descr>").append("<![CDATA[" + trackResonseDescr +"]]>").append("</track_response_descr>\r\n"); trackLevelDescr="";
                    
				}
				else if(currentColumn.trim().equalsIgnoreCase("role_code"))  //Item change for role_code
				{	
					roleCode = checkNull(genericUtility.getColumnValue("role_code", dom));
					if(roleCode != null && roleCode.trim().length() > 0)
					{
						//sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'ROLE_CODE' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ? ";
						sql = " SELECT DESCR   FROM WF_ROLE_USERS WRF,WF_ROLE WR WHERE WR.ROLE_CODE=WRF.ROLE_CODE  AND WRF.ROLE_CODE = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,roleCode.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							roleCodeDescr = rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						/*
						 * 
						 * Change the tag name for itemchange of role code
						 * Changes by Manoj Sarode on 20-Mar-2014  Start
						 *  
						 * */
	                    valueXmlString.append("<wf_role_descr>").append("<![CDATA[" + roleCodeDescr +"]]>").append("</wf_role_descr>\r\n"); 
					}
					else
					{
						 valueXmlString.append("<wf_role_descr>").append("<![CDATA[]]>").append("</wf_role_descr>\r\n");

							/*
							 * 
							 * Change the tag name for itemchange of role code
							 * Changes by Manoj Sarode on 20-Mar-2014 End
							 *  
							 * */
					}//end of role_code
				}
				else if(currentColumn.trim().equalsIgnoreCase("track_type"))  //Item change for track_type
				{	
					trackType = checkNull(genericUtility.getColumnValue("track_type", dom));
					if(trackType != null && trackType.trim().length() > 0)
					{
						sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_TYPE' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,trackType.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							trackTypeDescr = rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
	                    valueXmlString.append("<track_type_descr>").append("<![CDATA[" + trackTypeDescr +"]]>").append("</track_type_descr>\r\n"); 
					}
					else
					{
						   valueXmlString.append("<track_type_descr>").append("<![CDATA[]]>").append("</track_type_descr>\r\n");
					}//end of track_type
				}
				else if(currentColumn.trim().equalsIgnoreCase("track_level"))  //Item change for track_level
				{	
					trackLevel = checkNull(genericUtility.getColumnValue("track_level", dom));
					if(trackLevel != null && trackLevel.trim().length() > 0)
					{
						sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_LEVEL' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ?";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,trackLevel.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							trackLevelDescr = rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
	                    valueXmlString.append("<track_level_descr>").append("<![CDATA[" + trackLevelDescr +"]]>").append("</track_level_descr>\r\n"); 
					}
					else
					{
						  valueXmlString.append("<track_level_descr>").append("<![CDATA[]]>").append("</track_level_descr>\r\n");
					}//end of track_level
				}
				else if(currentColumn.trim().equalsIgnoreCase("track_response"))  //Item change for track_response
				{	
					trackResponse = checkNull(genericUtility.getColumnValue("track_response", dom));
					if(trackResponse != null && trackResponse.trim().length() > 0)
					{
						sql = " SELECT DESCR FROM GENCODES WHERE FLD_NAME = 'TRACK_RESPONSE' AND MOD_NAME ='W_TRACK_ACTS' AND FLD_VALUE = ? ";
						pstmt =  conn.prepareStatement(sql);
						pstmt.setString(1,trackResponse.trim());
						rs = pstmt.executeQuery();
						if(rs.next())
						{
							trackResonseDescr = rs.getString(1);
						}
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
	                    valueXmlString.append("<track_response_descr>").append("<![CDATA[" + trackResonseDescr +"]]>").append("</track_response_descr>\r\n"); 
					}
					else
					{
						 valueXmlString.append("<track_response_descr>").append("<![CDATA[]]>").append("</track_response_descr>\r\n");
					}//end of track_response
				}
				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;
	}
	
	
	public boolean isRecordExist(Connection conn , String tableName, String condition)
	{
	
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		String sql="";
		boolean isExist=false;
		int recCount=0;
		
		
		try
		{	
			
			sql = " SELECT  COUNT(*)  FROM  "+tableName +"  "+condition;
			pstmt =  conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				recCount=rs.getInt(1);
			
			}
			if(recCount>0)
			{
				isExist=true;
				
			}
			else
			{
				isExist=false;
			
			}
				
		}
		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();
			}
		}		
		
		System.out.print("---------Final--isExist-------"+isExist);
		return isExist;
	}
	
	

 
}	