
<%@ page import="java.util.*" %>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.IniHelper"%>
<%@ page import="com.eg.EgConfigFilesSync"%>
<%@ page import="com.eg.EgThresholdInfo"%>
<%@ page import="com.eg.EgConfigInfo"%>
<%@ page import ="egurkha.EgDbAdapterUI"%>
<%@ page import ="com.eg.EgDbAdapterTypeUI"%>
<%@ page import="com.eg.EgSpecsInfo" %>
<%@ page import="com.egurkha.util.StringUtils" %>
<%@ page import="java.sql.*" %>
<%@ page import = "net.sf.json.*"%>

<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%
     response.setHeader("Cache-Control","no-store");
     response.setHeader("Pragma","no-cache");
     response.setDateHeader("Expires", -1);
%>

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

<%
	JSONObject rootJson = new JSONObject();
	rootJson.put("success",true);

	String currentlyManaged = request.getParameter("currentValue");
	String previouslyManaged = request.getParameter("pfmanage");
	String mServers = request.getParameter("fmanage");
	EgThresholdInfo threshInfo = new EgThresholdInfo("manager");
	EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
	EgDbAdapterUI egDb;
	ResultSet rs = null;
	String status="";

	/* 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");
	auditLogThread.setValue("Activity","Global Thresholds");

	int count = 0;
	Vector cVector = new Vector();
	if(currentlyManaged !=null && !currentlyManaged.equalsIgnoreCase("null") && currentlyManaged.trim().length() >0)
	{
		StringTokenizer st = new StringTokenizer(currentlyManaged,",");
		if(st.countTokens()>0)
			while(st.hasMoreTokens())
				cVector.add(st.nextToken());
	}

	if(previouslyManaged !=null && !previouslyManaged.equalsIgnoreCase("null") && previouslyManaged.trim().length() >0)
	{
		StringTokenizer st = new StringTokenizer(previouslyManaged,",");
		if(st.countTokens()>0)
		{
			while(st.hasMoreTokens())
			{
				String temp = (String) st.nextToken();
				if(!cVector.contains(temp))
				{
					count++;
					auditLogThread.setCurrentValue("Disassociated Tests","$test$:"+temp);
				}
				else
					cVector.remove(temp);
			}
			if(count > 1)
				auditLogThread.setValue("Description","Tests have been associated/disassociated to global thresholds");
			else
				auditLogThread.setValue("Description","Test has been associated/disassociated to global thresholds");
		}
	}
	
	if(cVector.size()>0)
	{
		for(int i=0;i<cVector.size();i++)
			auditLogThread.setCurrentValue("Associated Tests","$test$:"+(String)cVector.get(i));		
		if(cVector.size()>1)
			auditLogThread.setValue("Description","Tests have been associated/disassociated to global thresholds");
		else
			auditLogThread.setValue("Description","Test has been associated/disassociated to global thresholds");
	}
	auditLogThread.sendItToDB();
	/* code for auditlog ends */


	String key = "";
	String value = "";
	String testName = "";

	ArrayList iniEntries = new ArrayList();
	ArrayList threshIniEntries = new ArrayList();
	ArrayList infoGrpIniEntries = new ArrayList();
	ArrayList testsToAssociate = new ArrayList();
	ArrayList testsToDisAssociate = new ArrayList();
	Enumeration e = request.getParameterNames();
	while(e.hasMoreElements())
	{
		key =(String) e.nextElement();
		value = request.getParameter(key);
		if (value != null && !value.equals(""))
		{
			StringTokenizer st = new StringTokenizer(value, "$$");
			while(st.hasMoreTokens())
			{
				testName = st.nextToken();
				int index = testName.indexOf("(");
				if(index != -1)
				{
					testName = testName.substring(0,index);
				}
				if(key != null && key.trim().equals("fmanage"))
				{
					iniEntries.add(new IniHelper(IniHelper.SET,"GLOBAL_THRESHOLDS",testName,"yes"));
					testsToAssociate.add(testName);
				}
				if(key != null && key.trim().equals("funmanage"))
				{
					testsToDisAssociate.add(testName);
					iniEntries.add(new IniHelper(IniHelper.DELETE,"GLOBAL_THRESHOLDS",testName,""));
				}
			}
		}
	}


	if (testsToAssociate != null)
	{
		prgBean.createFile("eg_thresholds.ini");
		//String defaultDescSubject = "DESCRIPTOR_DEFAULT_THRESHOLDS";
		String groupSubject = "THRESH_POLICY_MAPPING";
		String ruleSubject = "THRESHOLDPOLICIES";
		String subject = "Newtarget_Update_EgThresholdManager";

		String[] userThreshVal = prgBean.getVariables("USER_THRESHOLDS");
		String[] descThreshVal = prgBean.getVariables("DESCRIPTOR_THRESHOLDS");
		
		//default descriptor threshold
		//String[] defaultDescVars = prgBean.getVariables(defaultDescSubject);
		//ArrayList modifyDefaultDescTestList = new ArrayList();
		//IniFile resetDefaultIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/factory-config/eg_thresholds.ini");
		//String[] factoryDefaultDescVars = resetDefaultIni.getVariables(defaultDescSubject);

		//group threshold
		IniFile infoGroupIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_infogroup.ini");
		String[] threshPolicyVars = infoGroupIni.getVariables(groupSubject);
		String[] threshPolicyRuleVars = infoGroupIni.getVariables(ruleSubject);

		//if (defaultDescVars != null && defaultDescVars.length > 0)
		//{
			//for (int dd=0; dd<defaultDescVars.length; dd++)
			//{
				//String factDefaultDescVal = resetDefaultIni.getValue(defaultDescSubject,defaultDescVars[dd]);

				//if (factDefaultDescVal == null || factDefaultDescVal.length() == 0)
				//{
					//modifyDefaultDescTestList.add(defaultDescVars[dd]);
				//}
			//}
		//}

		//removing eg_threshupdate.ini starts here...
		IniFile threshUpdateIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
		String[] threshUpdateArrData = threshUpdateIni.getVariables(subject);
		ArrayList threshUpdateIniEntries = new ArrayList();

		//removing eg_threshupdate.ini ends here...

		for (int t=0;t<testsToAssociate.size();t++)
		{
			String strTestName = (String) testsToAssociate.get(t);
			if(descThreshVal.length > 0)
			{
				for(int r=0; r<descThreshVal.length; r++)
				{
					if(descThreshVal[r].startsWith(strTestName))
					{
						threshIniEntries.add(new IniHelper(IniHelper.DELETE,"DESCRIPTOR_THRESHOLDS",descThreshVal[r],""));
					}
				}
			}

			if(userThreshVal.length > 0)
			{
				for(int r=0; r<userThreshVal.length; r++)
				{
					if(userThreshVal[r].startsWith(strTestName))
					{
						threshIniEntries.add(new IniHelper(IniHelper.DELETE,"USER_THRESHOLDS",userThreshVal[r],""));
					}
				}
			}
			
			if(threshPolicyVars != null && threshPolicyVars.length > 0)
			{
				int x = threshPolicyVars.length;
				for(int ii=0;ii<x;ii++)
				{
					StringTokenizer stok = new StringTokenizer(threshPolicyVars[ii],"#");
					String servergroup = stok.nextToken();
					String grpTestName = stok.nextToken();
					if(grpTestName.startsWith(strTestName))
					{
						infoGrpIniEntries.add(new IniHelper(IniHelper.DELETE,groupSubject,threshPolicyVars[ii],""));
					}
				}
			}
			
			if(threshPolicyRuleVars != null && threshPolicyRuleVars.length > 0)
			{
				int x = threshPolicyRuleVars.length;
				for(int ii=0;ii<x;ii++)
				{
					String grpTestName = threshPolicyRuleVars[ii];
					if(grpTestName.startsWith(strTestName))
					{
						infoGrpIniEntries.add(new IniHelper(IniHelper.DELETE,ruleSubject,threshPolicyRuleVars[ii],""));
					}
				}
			}


			//removing eg_threshupdate.ini code starts here...
			if(threshUpdateArrData != null && threshUpdateArrData.length > 0 )
			{
				for(int tu=0;tu<threshUpdateArrData.length;tu++)
				{
					String tmpThreshUpdateData = threshUpdateArrData[tu];
					if(tmpThreshUpdateData.endsWith("#&#"+strTestName))
					{
						threshUpdateIniEntries.add(new IniHelper(IniHelper.DELETE,subject,tmpThreshUpdateData,""));

					}
				}
			}
			//removing eg_threshupdate.ini code ends here...


			//if(modifyDefaultDescTestList != null)
			//{
				//for(int r=0; r<modifyDefaultDescTestList.size(); r++)
				//{
					//if(modifyDefaultDescTestList.get(r).toString().startsWith(strTestName))
					//{
						//threshIniEntries.add(new IniHelper(IniHelper.DELETE,defaultDescSubject,(String)modifyDefaultDescTestList.get(r),""));
					//}
				//}
			//}
		}

		if (threshIniEntries != null && threshIniEntries.size() > 0)
		{
			IniFile threshIniSync = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + EgConfigInfo.egThresholdConfigFile);
			for (int i=0; i<threshIniEntries.size(); i++)
			{
				IniHelper ini = (IniHelper)threshIniEntries.get(i);
				String action = ini.getAction();
				String sub = ini.getSubject();
				String var = ini.getVariable();
				String val = ini.getValue();
				if (action != null && action.equals(IniHelper.DELETE))
				{
					threshIniSync.deleteValue(sub,var);
				}
			}
			threshIniSync.saveFile();
			EgConfigFilesSync.releaseInstance(threshIniSync);
		}

		if (infoGrpIniEntries != null && infoGrpIniEntries.size() > 0)
		{
			IniFile infoGrpSync = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + EgConfigInfo.egInfoGroupFile); 
			for (int i=0; i<infoGrpIniEntries.size(); i++)
			{
				IniHelper ini = (IniHelper)infoGrpIniEntries.get(i);
				String action = ini.getAction();
				String sub = ini.getSubject();
				String var = ini.getVariable();
				String val = ini.getValue();
				if (action != null && action.equals(IniHelper.DELETE))
				{
					infoGrpSync.deleteValue(sub,var);
				}
			}
			infoGrpSync.saveFile();
			EgConfigFilesSync.releaseInstance(infoGrpSync);
		}
		
		if (threshUpdateIniEntries != null && threshUpdateIniEntries.size() > 0)
		{
			IniFile threshUpdateIniObj = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
			for (int i=0; i<threshUpdateIniEntries.size(); i++)
			{
				IniHelper ini = (IniHelper)threshUpdateIniEntries.get(i);
				String action = ini.getAction();
				String sub = ini.getSubject();
				String var = ini.getVariable();
				String val = ini.getValue();
				if (action != null && action.equals(IniHelper.DELETE))
				{
					threshUpdateIniObj.deleteValue(sub,var);
				}
			}
			threshUpdateIniObj.saveFile();
			EgConfigFilesSync.releaseInstance(threshUpdateIniObj);
		}
	}

	if (testsToDisAssociate != null )
	{
		ArrayList threshUpdateIniEntries = new ArrayList();
		for (int d=0;d<testsToDisAssociate.size();d++)
		{
			String strDisTestName = (String) testsToDisAssociate.get(d);
			if(!StringUtils.isNull(strDisTestName))
			{
				Hashtable ht = new Hashtable();
				String subjectVal = "Newtarget_Update_EgThresholdManager";
				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='"+strDisTestName+"'" ;
						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+"#&#"+strDisTestName;
							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 ee)
				{
					if(rs != null)
					{
						rs.close();
					}
					egDb.releaseConnection(true);
					EgDbAdapterTypeUI.releaseObject(egDb);
					rootJson.put("success",false);
				}
				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);
					}
				}
				if(ht != null && ht.size() > 0)
				{
					for(int h=0;h<htKeyValues.size();h++)
					{
						String htKey = (String) htKeyValues.get(h);
						String htValues = (String) ht.get(htKey);
						threshUpdateIniEntries.add(new IniHelper(IniHelper.SET,subjectVal,htValues,strDisTestName));
					}
				}
			}
		}

		if(threshUpdateIniEntries != null)
		{
			IniFile serIniWr = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_threshupdate.ini");
			for (int i=0; i<threshUpdateIniEntries.size(); i++)
			{
				IniHelper ini = (IniHelper)threshUpdateIniEntries.get(i);
				String action = ini.getAction();
				String sub = ini.getSubject();
				String var = ini.getVariable();
				String val = ini.getValue();
				if (action != null && action.equals(IniHelper.SET))
				{
					serIniWr.setValue(sub,var,val);
				}
			}
			serIniWr.saveFile();
			EgConfigFilesSync.releaseInstance(serIniWr);
		}
	}
	
	HashMap nonSQCEntries = threshInfo.getNonSQCvaluesForGlobalThreshold(testsToAssociate);
	
	IniFile fileSyncThresh = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + EgConfigInfo.egThresholdConfigFile);
	IniFile fileSyncTests = EgConfigFilesSync.getInstance(EgConfigInfo.egMgrConfigDir + EgConfigInfo.egTestConfigFile); //eg_tests.ini
	for (int i=0; i<iniEntries.size(); i++)
	{
		IniHelper ini = (IniHelper)iniEntries.get(i);
		String action = ini.getAction();
		String sub = ini.getSubject();
		String var = ini.getVariable();
		String val = ini.getValue();
		if (action != null && action.equals(IniHelper.SET))
		{
			fileSyncTests.setValue(sub,var,val);
			String nonSQCEntry = (String)nonSQCEntries.get(var);
			if (nonSQCEntry != null && nonSQCEntry.length() > 0)
			{
				fileSyncThresh.setValue("DEFAULT_THRESHOLDS",var,nonSQCEntry);
			}
		}
		else if (action != null && action.equals(IniHelper.DELETE))
		{
			fileSyncTests.deleteValue(sub,var);
		}
	}
	fileSyncThresh.saveFile();
	fileSyncTests.saveFile();
	EgConfigFilesSync.releaseInstance(fileSyncTests);
	EgConfigFilesSync.releaseInstance(fileSyncThresh);
	
	String ur = "../../EgGlobalThresholdsConfig.jsp";

	out.println(rootJson.toString());

%>




