

/********************************************************
	Title     : TrackSetMaster.java
	Date      : 01-Feb-2014
	Developer : Manoj Sarode
	Purpose   : Define the the tracking set with multiple activities.
********************************************************/

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 TrackSetMaster extends ValidatorEJB implements TrackSetMasterLocal,TrackSetMasterRemote
{
	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 trackSetCode = "";
		String errString = "";
		String actCode ="";
		String seqNo ="";
		String expCompDays ="";
		String trackShDesc ="";
		String trackDesc ="";
		String updateFlag ="";
		int currentFormNo = 0;
		int childNodeListLength;
		int childNodeLength;
		int ctr=0;
		int count = 0;
		
		boolean flag = false;
		NodeList parentNodeList = null;
		NodeList parentNodeListCheck = null;
		NodeList childNodeList = null;	
		Node parentNode = null;
		Node childNode = null;
	
		
		ArrayList<String> errList = new ArrayList<String>();
		ArrayList<String> errFields = new ArrayList<String>();
		//Map<String,String> actCodeList = new HashMap<String,String>();
		ArrayList<String> actCodeList=new ArrayList<String>();
		ArrayList<String> trackSetList=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("track_set") )     // Validation for track_set code
					{
						trackSetCode = checkNull(genericUtility.getColumnValue("track_set", curDom));
						if(trackSetCode == null || trackSetCode.trim().length() == 0)
						{
							errCode = "VTBLKTRKST";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							flag = isRecordExist(conn," TRAN_TRACK_SET "," WHERE TRACK_SET ='"+trackSetCode.trim()+"' ");
							if(flag == true && editFlag.equalsIgnoreCase("A"))
							{
								errCode = "VTTRKSTEXT";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
							
							//@SANTOSH CHECK VALIDATION FOR TRACK SET CODE FROM BOTH HEADER AND DETAIL SCREEN ARE SAME
							System.out.println("edit "+editFlag+" Update "+updateFlag);
							if (allDom != null && editFlag.equalsIgnoreCase("A"))
							{
								NodeList childNodeListLocal = null;	
								Node parentNodeLocal = null;
								Node childNodeLocal = null;
								
								parentNodeListCheck = allDom.getElementsByTagName("Detail2");
								childNodeLength = parentNodeListCheck.getLength();
							    String tempTrackSet = "";
							    trackSetList.clear();
								for (int selectedRow = 0; selectedRow < childNodeLength; selectedRow++)
								{
									parentNodeLocal = parentNodeListCheck.item(selectedRow);
									childNodeListLocal = parentNodeLocal.getChildNodes();
									int childNodeListLengthLocal = childNodeListLocal.getLength();
									updateFlag = getAttribValue(parentNodeLocal,"attribute", "updateFlag"); 
									if(!updateFlag.equalsIgnoreCase("D"))
									{
										for (int childRow = 0; childRow < childNodeListLengthLocal; childRow++)
										{
											childNodeLocal = childNodeListLocal.item(childRow);
											String childNodeNameLocal = childNodeLocal.getNodeName();
											if(childNodeLocal.getFirstChild()!=null)
											{
												if (childNodeNameLocal.equals("track_set")) 
												{
													tempTrackSet = childNodeLocal.getFirstChild().getNodeValue();
												}
											}
										}
										System.out.println("BEFORE MAP trackSetList : "+trackSetList);
										if (trackSetList.contains(tempTrackSet.trim()))
										{
										}
										else
										{
											trackSetList.add(tempTrackSet.trim());	
											System.out.println("AFTER ADD : "+trackSetList);
										}
									}
								}
							}
							
							if(editFlag!=null && editFlag.equalsIgnoreCase("A"))
							{
								for (int i = 0; i < trackSetList.size(); i++) 
								{
									if(trackSetList.get(i).equalsIgnoreCase(trackSetCode))
									{
									}
									else
									{
										// track set on header and detail screen are not same,
										errCode = "VTINVTRCD2";
										errList.add(errCode);
										errFields.add(childNodeName.toLowerCase());
										break;
									}
								}
							}
						}
					}   //track_set end
					else if(childNodeName.equalsIgnoreCase("sh_descr")) // Validation for Track Set Short Description 
					{
						trackShDesc = 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 Track Set Description 
					{
						trackDesc = checkNull(genericUtility.getColumnValue("descr", curDom));
						if(trackDesc == null || trackDesc.trim().length() == 0)
						{
							errCode = "VTBLNKDSCR";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
					} // End of descr 
					
				}
				 break;
			
			case 2 :
				parentNodeList = curDom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				childNodeListLength = childNodeList.getLength();
				String actCodeCheck = "";
				for(ctr = 0; ctr < childNodeListLength; ctr ++)
				{
					childNode = childNodeList.item(ctr);
					childNodeName = childNode.getNodeName();
					
					if(childNodeName.equalsIgnoreCase("act_code") )     // 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 == false )
							{
								errCode = "VTINVACVCD";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						
						/*
						 *  Logic to check the repeat entry for Activity Code is exists or not.
						 *  
						 * */
						actCodeCheck = checkNull(genericUtility.getColumnValue("act_code", curDom));
						if (allDom != null ) {
						parentNodeListCheck = allDom.getElementsByTagName("Detail2");
						childNodeLength = parentNodeListCheck.getLength();
					    String tempActCode = "";
					    actCodeList.clear();
						for (int selectedRow = 0; selectedRow < childNodeLength; selectedRow++)
						{
							parentNode = parentNodeListCheck.item(selectedRow);
							childNodeList = parentNode.getChildNodes();
							childNodeListLength = childNodeList.getLength();
							updateFlag = getAttribValue(parentNode,"attribute", "updateFlag"); 
							if(!updateFlag.equalsIgnoreCase("D"))
							{
								for (int childRow = 0; childRow < childNodeListLength; childRow++)
								{
									childNode = childNodeList.item(childRow);
									childNodeName = childNode.getNodeName();
									if(childNode.getFirstChild()!=null)
									{
										if (childNodeName.equals("act_code")) 
										{
											tempActCode = childNode.getFirstChild().getNodeValue().trim();
											//actCodeList.put(tempActCode,tempActCode);
										}
									}
								}
								System.out.println("BEFORE actCodeList : "+actCodeList);
								if (actCodeList.contains(tempActCode))
								{
									errCode = "VTENTRYEXT";
									errList.add(errCode);
									errFields.add(childNodeName.toLowerCase());
								}
								else
								{
									actCodeList.add(tempActCode);	
									System.out.println("AFTER ADD : "+actCodeList);
								}
							}
						}
					}
					}   //act_code end
					else if(childNodeName.equalsIgnoreCase("seq_no") )     // Validation for seq_no
					{
						seqNo = checkNull(genericUtility.getColumnValue("seq_no", curDom));
					
						
						
						/*
						 * 
						 * Add the condition for sequence no i.e it can not be zero or negetive. 
						 * Changes by Manoj Sarode on 20-Mar-2014 as discussed with PPatro sir. Start
						 *  
						 * */
						if(seqNo == null || seqNo.trim().length() == 0)
						{
							errCode = "VTBLKSEQNO";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else {
							int sno = Integer.parseInt(seqNo);
							if( sno==0 ||sno< 0)
							{
								errCode = "VMINVSEQNO";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						

						/*
						 * 
						 * Add the condition for sequence no i.e it can not be zero or negetive. 
						 * Changes by Manoj Sarode on 20-Mar-2014 as discussed with PPatro sir. End
						 *  
						 * */
						
					}   //seq_no end
					else if(childNodeName.equalsIgnoreCase("exp_comp_days") )     // Validation for exp_comp_days
					{
						expCompDays = checkNull(genericUtility.getColumnValue("exp_comp_days", curDom));
						
						
						if(expCompDays == null || expCompDays.trim().length() == 0)
						{
							errCode = "VTBLKEXPDY";
							errList.add(errCode);
							errFields.add(childNodeName.toLowerCase());
						}
						else
						{
							double expComDaysDouble = Double.parseDouble(expCompDays) ;
							if(expComDaysDouble <= 0)
							{
								errCode = "VMINVEXPDY";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
						   //exp_comp_days end
				}
					//Code commented by Santosh 14-03-2014 as per suggetsed by Hemant Sir -- Product code field removed from Metadata
					/*else if(childNodeName.equalsIgnoreCase("product_code")) // Validation for   product_code 
					{
						
						String productCode = checkNull(genericUtility.getColumnValue("product_code", curDom));
						if(productCode != null && productCode.trim().length() > 0)
						{
							flag = isRecordExist(conn," ITEM "," WHERE ITEM_CODE ='"+productCode.trim()+"' ");
							
							if(flag == false)
							{
								errCode = "VTINVPDCOD";
								errList.add(errCode);
								errFields.add(childNodeName.toLowerCase());
							}
						}
					}	*/
				}
			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 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 : [TrackSetMaster][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 actCode = "";
		String actCodeDescr = "";
		String itemCodeDescr="";
		
		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);
			
			
				valueXmlString.append("</Detail1>");
				break;    
				
			case 2 :
				
				parentNodeList = dom.getElementsByTagName("Detail2");
				parentNode = parentNodeList.item(0);
				childNodeList = parentNode.getChildNodes();
				valueXmlString.append("<Detail2>");
				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("act_code"))  //Item change for activity code
					{	
					 actCode = checkNull(genericUtility.getColumnValue("act_code", dom));
						if(actCode != null && actCode.trim().length() > 0)
						{
							sql = " SELECT DESCR FROM TRAN_TRACK_ACTS WHERE ACT_CODE = ? ";
							pstmt =  conn.prepareStatement(sql);
							pstmt.setString(1,actCode.trim());
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								actCodeDescr = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
		                    valueXmlString.append("<tran_track_acts_descr>").append("<![CDATA[" + actCodeDescr +"]]>").append("</tran_track_acts_descr>\r\n"); 
						}
						else
						{
							 valueXmlString.append("<tran_track_acts_descr>").append("<![CDATA[]]>").append("</tran_track_acts_descr>\r\n");
						}//end of act_code
					}
				//Code commented by Santosh 14-03-2014 as per suggetsed by Hemant Sir -- Product code field removed from Metadata
				 /* else if(childNodeName.equalsIgnoreCase("product_code")) // Validation for product_code Description 
					{
					
					 
					 String productCode = checkNull(genericUtility.getColumnValue("product_code", dom));
						if(productCode != null && productCode.trim().length() > 0)
						{
							sql="SELECT DESCR FROM ITEM WHERE ITEM_CODE = ?";
							pstmt =  conn.prepareStatement(sql);
							pstmt.setString(1,productCode.trim());
							rs = pstmt.executeQuery();
							if(rs.next())
							{
								itemCodeDescr = rs.getString(1);
							}
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
		                    valueXmlString.append("<item_descr>").append("<![CDATA[" + itemCodeDescr +"]]>").append("</item_descr>\r\n"); 
						}
						else
						{
							 valueXmlString.append("<item_descr>").append("<![CDATA[]]>").append("</item_descr>\r\n");
						}
					}*/
				 valueXmlString.append("</Detail2>");
				 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;
	}
	
	

	private String getAttribValue(Node detailNode, String nodeName, String attribStr)
	{
		String attribValue = "";
		try
		{
			String domStr = GenericUtility.getInstance().serializeDom(detailNode);
			Document dom = GenericUtility.getInstance().parseString(domStr);
			if( dom != null /*&& dom.getAttributes() != null*/)
			{
				Node attributeNode = dom.getElementsByTagName( nodeName ).item(0);
				attribValue = getAttribValue(attributeNode, attribStr);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
	private String getAttribValue(Node detailNode, String attribStr)
	{
		String attribValue = "";
		try
		{
			if( detailNode != null && detailNode.getAttributes() != null)
			{
				Node attribNode = detailNode.getAttributes().getNamedItem( attribStr );
				if( attribNode != null )
				{
					attribValue = checkNull( attribNode.getNodeValue() );
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
	
 
}	