<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import = "java.lang.*" %>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgMappingInfo"%>
<%@ page import="com.eg.IniFile" %>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import ="egurkha.EgDbAdapterUI"%>
<%@ page import ="com.eg.EgDbAdapterTypeUI"%>
<%@ page import="com.eg.UpdateAndTransmitTrendInfo" %>
<%@ page import="com.eg.EgTesterInfo" %>
<%@ page import="com.eg.EgDateInfo" %>
<%@ page import="com.eg.EgDbInfo" %>
<%@ page import="com.eg.EgThresholdInfo" %>
<%@ page import="com.eg.EgSpecsInfo" %>
<%@ page import="com.eg.EgConfigInfo" %>
<%@ page import="com.eg.EgDiscInfo" %>
<%@ page import="com.eg.EgDiscInfo2" %>
<%@ page import="com.eg.EgServerGroupBean" %>
<%@ page import="net.sf.json.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<jsp:useBean id="prgBean" class="egurkha.EgTestParamBean" scope="page" />
<jsp:useBean id="threshBean" class="egurkha.EgThresholdBean" scope="page" />

<%
	JSONObject rootJson = new JSONObject();
	IniUI iniUI = IniUI.getInstance();
	//user language
	String userLanguage = iniUI.getDefaultLanguage();
	EgDbAdapterUI egDb;
	EgDateInfo dat=new EgDateInfo();
	EgDbInfo dbInfo=new EgDbInfo("manager");
	EgThresholdInfo dbThresh =new EgThresholdInfo("manager");
	EgTesterInfo testerInfo =new EgTesterInfo("manager");
	EgSpecsInfo egSpecs = new EgSpecsInfo("manager");
	EgDiscInfo egDiscs = new EgDiscInfo("manager");
	EgDiscInfo2 discInfo2 = new EgDiscInfo2("manager");
	EgConfigInfo configInfo = new EgConfigInfo("manager");
	EgServerGroupBean serverGrpBean = new EgServerGroupBean();

	ResultSet rs = null;
	String status ="";
	ArrayList threshGrpTestList = new ArrayList();
	TreeSet threshGrpTreeSet = serverGrpBean.getTestColnComponentsForServerType();
	threshGrpTestList.addAll(threshGrpTreeSet);
	UpdateAndTransmitTrendInfo updateHelper = new UpdateAndTransmitTrendInfo();
	IniFile servicesIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	boolean isUpdateToDb= "true".equalsIgnoreCase(servicesIni.getValue("MISC_ARGS","updateDefaultThreshToDb"));
	ArrayList globalThresholds=testerInfo.getGlobalThresholds();
	if (globalThresholds == null || globalThresholds.isEmpty())
	{
		globalThresholds = new ArrayList();
	}

	if (_user != null)
	{
		userLanguage = _user.getLanguage();
	}
	EgMappingInfo mappingInfo = new EgMappingInfo(userLanguage);
	String operation = request.getParameter("operation");
	String que="";
	String measUpdate="";
	String threshUpdate="";
	String minUpdate="";
	String maxUpdate="";
	String currentTime="";
	String threshTable="";
	String trgtHost="";
	String port="";
	String startTime="";
	Vector host = new Vector();
	Vector sid = new Vector();
	String user_thresh = "USER_THRESHOLDS";
	String descr_thresh = "DESCRIPTOR_THRESHOLDS"; // SIFY
	StringTokenizer st1 = null;

	long tim = 0l;
	long current = 0l;
	String time="";
	String measur="";

	if (operation.equals("alarmPolicyDesc"))
	{
		String alarmPolicy = request.getParameter("alarmPolicy");
		IniFile thresholdsIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini");
		String strDescription = thresholdsIni.getValue("ALARM_POLICY",alarmPolicy);
		int i_idx = strDescription.indexOf(",");
		String windowSize = strDescription.substring(0,i_idx);
		String numCrossings = strDescription.substring(i_idx+1);
		if (windowSize.equals("1") && numCrossings.equals("1"))
		{
			out.println(numCrossings + " threshold violation out of " + windowSize + " measurement");
		}
		else
		{
			out.println(numCrossings + " threshold violations out of " + windowSize + " measurements");
		}
	}
	else if(operation.equals("updateThresholds"))
	{
		String strComponentType = request.getParameter("componentType");
		String testName = request.getParameter("testName");
		String threshold = request.getParameter("threshold");
		String measure = threshold.substring(0,threshold.indexOf(":"));
		measure+=":";
		String newDefaultThreshold = "";
		StringBuffer strbuffer = new StringBuffer();
		IniFile defaultIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini");
		String defaultThreshold = defaultIni.getValue("DEFAULT_THRESHOLDS",testName);
		ArrayList previousValues = new ArrayList();
		StringTokenizer st = new StringTokenizer(defaultThreshold,",");
		while (st.hasMoreTokens())
		{
			String strTok = st.nextToken();
			previousValues.add(strTok);
			if (strTok.startsWith(measure))
			{
				strbuffer.append(threshold).append(",");
			}
			else
			{
				strbuffer.append(strTok).append(",");
			}
		}

		/* code for auditlog starts */
		AuditLogThread auditLogThread = new AuditLogThread();	
		auditLogThread.setValue("Category","Admin");
		auditLogThread.setValue("User_id",_user.getLoginID());
		auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
		auditLogThread.setValue("Session_id",session.getId());
		auditLogThread.setValue("Module","Thresholds");

		for(int i=0;i<previousValues.size();i++)
		{
			String preData = (String) previousValues.get(i);
			if(preData.startsWith(measure))
			{
				ArrayList tempPrevious = StringUtils.egTokenizer(preData,":");
				ArrayList tempCurrent = StringUtils.egTokenizer(threshold,":");

				String auditMeasure = "$measure$:"+testName+":"+tempPrevious.get(0).toString().trim();
				String previousMin = tempPrevious.get(2).toString().trim();
				String previousMax = tempPrevious.get(3).toString().trim();
				String alarmPolicyPrevious = tempPrevious.get(4).toString().trim();

				String currentMin = tempCurrent.get(2).toString().trim();
				String currentMax = tempCurrent.get(3).toString().trim();
				String alarmPolicyCurrent = tempCurrent.get(4).toString().trim();

				if(!previousMin.equals(currentMin))
				{
					if(previousMin.equals("-1"))
					{
						previousMin = "none";
					}
					if(currentMin.equals("-1"))
					{
						currentMin = "none";
					}
					auditLogThread.setPreviousValue(auditMeasure,"Minimum-Threshold " + previousMin);
					auditLogThread.setCurrentValue(auditMeasure,"Minimum-Threshold " + currentMin);
				}

				if(!previousMax.equals(currentMax))
				{
					if(previousMax.equals("-1"))
					{
						previousMax = "none";
					}
					if(currentMax.equals("-1"))
					{
						currentMax = "none";
					}
					auditLogThread.setPreviousValue(auditMeasure,"Maximum-Threshold " + previousMax);
					auditLogThread.setCurrentValue(auditMeasure,"Maximum-Threshold " + currentMax);
				}

				if(!alarmPolicyPrevious.equals(alarmPolicyCurrent))
				{
					auditLogThread.setPreviousValue(auditMeasure,"Alarms " + alarmPolicyPrevious);
					auditLogThread.setCurrentValue(auditMeasure,"Alarms " + alarmPolicyCurrent);
				}
			}
		}
		auditLogThread.setValue("Activity","Configure Thresholds");
		if (!StringUtils.isNull(strComponentType))
		{
			auditLogThread.setValue("Description","The default thresholds for " + mappingInfo.getTestDescription(testName) + " test of " + mappingInfo.getComponentTypeDescription(strComponentType) + " have been modified");
		}
		else
		{
			auditLogThread.setValue("Description","The default thresholds for " + mappingInfo.getTestDescription(testName) + " test have been modified");
		}
		auditLogThread.sendItToDB();
	
		/* code for auditlog ends */

		// DB updation code starts
		prgBean.createFile("eg_thresholds.ini");
		String[] userThreshVal = prgBean.getVariables(user_thresh);
		ArrayList getAllCompsForServer = getAllManagedComps();

		ArrayList userThreshList = new ArrayList();
		ArrayList descThreshList = new ArrayList();
		ArrayList hostLevelTests = (ArrayList) session.getAttribute("sessListHostLevelTests");
		if(userThreshVal.length > 0)
		{
			for(int r=0; r<userThreshVal.length; r++)
			{
				if(userThreshVal[r].startsWith(testName))
				{
					userThreshList.add(userThreshVal[r]);
				}
			}
		}
		String []descThreshVal = prgBean.getVariables(descr_thresh);
		if(descThreshVal.length > 0)
		{
			for(int r=0; r<descThreshVal.length; r++)
			{
				if(descThreshVal[r].startsWith(testName))
				{
					descThreshList.add(descThreshVal[r]);
				}
			}
		}

//		if(isUpdateToDb && !globalThresholds.contains(testName))
//		{
//			egDb=EgDbAdapterTypeUI.getObject();
//			try
//			{
//				ArrayList a = new ArrayList();
//				ArrayList minarray=new ArrayList();
//				ArrayList maxarray=new ArrayList();
//				ArrayList parametersToSec= new ArrayList();
//				startTime=dbInfo.measurementStartTimeColumn;
//				trgtHost=dbInfo.targetHostColumn;
//				port= dbInfo.portNoColumn;
//				currentTime=dat.egetDate();
//
//				for(int y=0;y<previousValues.size();y++)
//				{
//					ArrayList params = new ArrayList();
//					String preData = (String) previousValues.get(y);
//					if(preData.startsWith(measure))
//					{
//						threshTable = dbInfo.getThresholdTableForTest(testName);
//						st = new StringTokenizer(threshold,":");
//						measUpdate=st.nextToken();
//						threshUpdate=st.nextToken();
//						minUpdate=st.nextToken();
//						if(minUpdate.equals("none"))
//							minUpdate="-1";
//						maxUpdate=st.nextToken();
//						if(maxUpdate.equals("none"))
//							maxUpdate="-1";
//						time=dbInfo.dbDate(currentTime);
//						tim=dat.egetUTCDate();
//						current=(threshBean.trimTimeToHr(tim))-1000;
//						time = dat.egetDate(current);
//						String measures[] =dbThresh.
//						getMeasurementsForTest(testName);
//						String[] mColumns=new String[2];
//						mColumns = dbInfo.getThresholdColumnsForMeasure(testName,measures[y]);
//						int place=mColumns[0].lastIndexOf("_MIN");
//						measur=mColumns[0].substring(0,place);
//
//						if(threshUpdate != null && threshUpdate.equals("mix"))
//						{
//							if (minUpdate.indexOf("sqc") > -1 || maxUpdate.indexOf("sqc") > -1)
//							{
//								a.add(measur);
//								if(minUpdate.equals("-1") || minUpdate.indexOf("sqc") > -1)
//								{
//									minarray.add(minUpdate);
//								}
//								else
//								{
//									minarray.add("sqc");
//								}
//								if(maxUpdate.equals("-1") || maxUpdate.indexOf("sqc") > -1)
//								{
//									maxarray.add(maxUpdate);
//								}
//								else
//								{
//									maxarray.add("sqc");
//								}
//							}
//							else
//							{
//								params.add(threshTable);
//								params.add(mColumns);
//								params.add(minUpdate);
//								params.add(maxUpdate);
//								params.add(startTime);
//								params.add(time);
//								params.add(que);
//								params.add(trgtHost);
//								params.add(port);
//								params.add(host);
//								params.add(dbInfo.infoColumn);
//								params.add(sid);
//								parametersToSec.add(params);
//							}
//						}
//					}
//				}
//				if(parametersToSec.size()>0)
//				{
//					boolean result = updateHelper.updateThresholds(parametersToSec,"Default");
//				}
//				if(a.size()>0)
//				{
//					String [] measures = new String[a.size()];
//					String [] minVal = new String[minarray.size()];
//					String [] maxVal = new String[maxarray.size()];
//					for(int g=0; g<a.size();g++)
//					{
//						measures[g]=(String)a.get(g);
//						minVal[g]=(String)minarray.get(g);
//						maxVal[g]=(String)maxarray.get(g);
//					}
//					updateHelper.computeThresholds(testName,
//						measures,minVal,maxVal,tim,
//						"default","null","null","null","null"); // SIFY
//				}
//				EgDbAdapterTypeUI.releaseObject(egDb);
//			}
//			catch(Exception e)
//			{
//				//System.out.println("Error Updating DataBase");
//				if(egDb != null)
//					EgDbAdapterTypeUI.releaseObject(egDb);
//			}
//		}

// new ini entry code starts here
		ArrayList infoBasedGroupList = new ArrayList();
		ArrayList groupTestsList = new ArrayList();
		ArrayList tmpManagedInfos = new ArrayList();
		TreeSet managedInfos = serverGrpBean.getAllManagedInfosForTest(testName);
		tmpManagedInfos.addAll(managedInfos);
		for(int g=0;g<getAllCompsForServer.size(); g++)
		{
			String component = (String) getAllCompsForServer.get(g);
			String tmpComp = "";
			if(hostLevelTests.contains(testName))
			{
				tmpComp = component.substring(0,component.indexOf(":"));
				tmpComp +=":NULL";
			}
			else
			{
				tmpComp = component;
			}

			if(!serverGrpBean.isServerAssociatedToTest(component,testName) && serverGrpBean.isServerAssociatedToTestUI(component,testName))
			{
				if(tmpManagedInfos != null && tmpManagedInfos.size() > 0)
				{
					for(int v=0;v<tmpManagedInfos.size();v++)
					{
						String vecInfo = (String) tmpManagedInfos.get(v);
						infoBasedGroupList.add(testName+":"+tmpComp+"#"+vecInfo);
					}
				}
			}

			if(serverGrpBean.isServerAssociatedToTest(component,testName))
			{
				groupTestsList.add(testName+":"+tmpComp);
				continue;
			}

		}
		//Vector vec = dbThresh.getInfosForThresholds(test,component);
		//boolean b_portRelev = egSpecs.isPortRelevantForTest(testName);
		//Vector serverGroup = serverGrpBean.getServerGroup(component,test,b_portRelev);
		if(!StringUtils.isNull(testName) && !globalThresholds.contains(testName))
		{
			Vector allVariablesVec = new Vector();
			Vector allValuesVec = new Vector();

			Hashtable ht = new Hashtable();
			boolean isSaveIni = false;
			egDb=EgDbAdapterTypeUI.getObject();
			try
			{
				boolean isConnected = false;
				status = egDb.setConnection();
				if(status.equals("CONNECTED"))
				{
					isConnected = true;
				}
				if(isConnected)
				{
					String query ="SELECT TRGT_HOST,PORT_NO,SITE_NAME,INFO,MSMT_HOST FROM MEASURE_LAST WHERE TEST_NAME='"+testName+"'" ;
					rs = egDb.SelectExec(query);
					while(rs.next())
					{
						String hostVal = rs.getString(1);
						String portVal = rs.getString(2);
						String siteVal = rs.getString(3);
						String infoVal = rs.getString(4);
						String msmthostVal = rs.getString(5);

						String updateDbData = hostVal+"#&#"+portVal+"#&#"+siteVal+"#&#"+StringUtils.encodeSecurityChar(infoVal)+"#&#"+msmthostVal+"#&#"+testName;
						int r = infoVal.indexOf(EgConfigInfo.infoFieldSeparator);
						String str_info="";
						String sidVal="";
						if(r != -1)
						{
							str_info = infoVal.substring(r+1).trim();
							sidVal = infoVal.substring(0,r);
						}
						if(StringUtils.isNull(sidVal))
						{
							ht.put(hostVal+":"+portVal+"#"+infoVal+"#"+msmthostVal,updateDbData);
						}
						else
						{
							ht.put(hostVal+":"+portVal+":"+sidVal+"#"+infoVal+"#"+msmthostVal,updateDbData);
						}
					}
				}
				rs.close();
				egDb.releaseConnection(false);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			catch(Exception e)
			{
				if(rs != null)
				{
					rs.close();
				}
				egDb.releaseConnection(true);
				EgDbAdapterTypeUI.releaseObject(egDb);
			}
			ArrayList htKeyValues = new ArrayList();
			if(ht != null && ht.size() > 0)
			{
				Iterator iterAll = ht.keySet().iterator();
				while(iterAll.hasNext())
				{
					String tempKeys = (String) iterAll.next();
					htKeyValues.add(tempKeys);
				}
			}

			for(int ct = 0;ct<getAllCompsForServer.size();ct++)
			{
				String tempComp = (String)getAllCompsForServer.get(ct);
				String tmpTrgtHost = tempComp.substring(0,tempComp.indexOf(":"));
				if(hostLevelTests.contains(testName))
				{
					if(!tempComp.endsWith(":NULL"))
					{
						tempComp = tempComp.substring(0,tempComp.indexOf(":"));
						tempComp+=":NULL";
					}
				}
				if(ht != null && ht.size() > 0)
				{
					for(int h=0;h<htKeyValues.size();h++)
					{
						String htKey = (String) htKeyValues.get(h);
						String infoData = htKey.substring(htKey.indexOf("#")+1);
						infoData = infoData.substring(0,infoData.indexOf("#"));
						int r = infoData.indexOf(EgConfigInfo.infoFieldSeparator);
						String str_info="";
						String sidVal="";
						if(r != -1)
						{
							str_info = infoData.substring(r+1).trim();
							sidVal = infoData.substring(0,r);
						}

						if(htKey.startsWith(tempComp))
						{
							if(hostLevelTests.contains(testName))
							{
								String strUserVal = testName+":"+tmpTrgtHost;
								String strGrpVal = testName+":"+tempComp;
								String nickWithNullPort = tmpTrgtHost+":NULL";
								String strDescVal = testName+":"+nickWithNullPort+"#"+StringUtils.encodeSecurityChar(str_info);
								String strGrpDescVal = testName+":"+nickWithNullPort+"#"+str_info; // upgrade and group desc checking
								if(userThreshList != null && userThreshList.contains(strUserVal))
								{
									break;
								}
								else if((descThreshList != null && (descThreshList.contains(strDescVal) || descThreshList.contains(strGrpDescVal))) || (infoBasedGroupList != null && infoBasedGroupList.contains(strGrpDescVal)))
								{
									continue;
								}
								else if(groupTestsList != null && groupTestsList.contains(strGrpVal))
								{
									continue;
								}
								else
								{
									String htValues = (String) ht.get(htKey);
									isSaveIni = true;
									allVariablesVec.add(htValues);
									allValuesVec.add(testName);
									//serIniWr.setValue(subjectVal,htValues,testName);
								}
							}
							else
							{
								String strUserVal = testName+":"+tempComp;
								String strDescVal = testName+":"+tempComp+"#"+StringUtils.encodeSecurityChar(str_info);
								String strGrpDescVal = testName+":"+tempComp+"#"+str_info; // upgrade and group desc checking

								if((userThreshList != null && userThreshList.contains(strUserVal))  )
								{
									break;
								}
								else if((descThreshList != null && (descThreshList.contains(strDescVal) ||descThreshList.contains(strGrpDescVal))) || (infoBasedGroupList != null && infoBasedGroupList.contains(strGrpDescVal)))
								{
									continue;
								}
								else if(groupTestsList != null && groupTestsList.contains(strUserVal))
								{
									continue;
								}
								else
								{
									String htValues = (String) ht.get(htKey);
									isSaveIni = true;
									//serIniWr.setValue(subjectVal,htValues,testName);
									allVariablesVec.add(htValues);
									allValuesVec.add(testName);
								}
							}
						}
					}
				}
			}

			if (isSaveIni)
			{
				if (allVariablesVec != null && allVariablesVec.size() > 0)
				{
					String subjectVal = "Newtarget_Update_EgThresholdManager";
					IniFile serIniWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
					serIniWr.setValues(subjectVal, allVariablesVec, allValuesVec, false);
					serIniWr.saveFile();
					EgConfigFilesSync.releaseInstance(serIniWr);
				}
			}
		}
		rootJson.put("successUpdate",true);

		//DB updation code ends
		newDefaultThreshold = strbuffer.toString();
		int len = newDefaultThreshold.length()-1;
		newDefaultThreshold = newDefaultThreshold.substring(0,len);

		String strThresholdIni = EgInstallInfo.getInstallDir()+"/manager/config/eg_thresholds.ini";
		IniFile ThresholdIniWrite = EgConfigFilesSync.getInstance(strThresholdIni);
		ThresholdIniWrite.setValue("DEFAULT_THRESHOLDS",testName,newDefaultThreshold);
		ThresholdIniWrite.saveFile();
		EgConfigFilesSync.releaseInstance(ThresholdIniWrite);
	}
	out.println(rootJson.toString());
%>

<%!

	public ArrayList getAllManagedComps()
	{
		ArrayList aListPorts = new ArrayList();
		EgDiscInfo2 discInfo2 = new EgDiscInfo2("manager");
		List allHosts = discInfo2.getAllManagedComponents();
		for (int i=0;i<allHosts.size();i++)
		{
			String strTemp = "";
			String allData = (String)allHosts.get(i);
			StringTokenizer st = new StringTokenizer(allData,",");
			String serType = st.nextToken();
			String ipVal = st.nextToken();
			String nick = "";
			String port = "";
			String sid = "";
			if(serType.equals("Oracle_server"))
			{
				nick = st.nextToken();
				port = st.nextToken();
				String isPassive = st.nextToken();
				if (!st.hasMoreTokens())
					continue;
				sid = st.nextToken();
				strTemp = nick+":"+port+":"+sid;
			}
			else
			{
				nick = st.nextToken();
				port = st.nextToken();
				strTemp = nick+":"+port;
			}
			aListPorts.add(strTemp);
		}
		return aListPorts;
	}
%>