<%
/*
 *		Name		:		EgconfigsnmpmeasurepJson.jsp
 *		Purpose		:		IC Test - SNMP Type - Configure process page
 */
%>

<%@ include file = "../../../admin/EgTrackerAJSON.jsp"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import="egurkha.*" %>
<%@ page import="net.sf.json.JSONObject"%>

<%! 
	private int getDbSize(int s)
	{
		int size=-1;
		switch(s)
		{
			case 1:size=32;break;
			case 2:size=64;break;
			case 3:size=128;break;
			case 4:size=256;break;
			case 5:size=512;break;
			case 6:size=1024;break;
		}
		return size;
	}
%>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
	
	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");

	Hashtable factorsMapping = new Hashtable();
	//factorsMapping = (Hashtable) session.getAttribute("factorsMapping");
	//session.removeAttribute("factorsMapping");
	IniFile iniUI = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	String factors [] = iniUI.getVariables("CONVERSION_FACTORS");
	if(factors != null && factors.length > 0)
	{
		for (int i=0;i<factors.length;i++)
		{
			String var = (String) factors[i];
			String val = iniUI.getValue("CONVERSION_FACTORS", var);
			factorsMapping.put(val, var);
		}		
	}

	//IniFile iniFile=new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_udtests.ini",true);
	/* 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","Integration Console");
	auditLogThread.setValue("Activity","Configure Test");
	/* code for auditlog ends */
	String add = request.getParameter("add");
	String test = request.getParameter("test");
	String measure = request.getParameter("measure");
	String dbSize = request.getParameter("dbsize");
	String unitA = request.getParameter("otherunit");
	String unitB = request.getParameter("un");
	String index = request.getParameter("index");
	String process = request.getParameter("process");
	String oid = request.getParameter("oid");
	String restdatafld = request.getParameter("restdatafld");
	String restParentNode = request.getParameter("restParentNode");
	String fileName=request.getParameter("fileName");
	String element_fileName=request.getParameter("element_fileName");
	String status_fileName=request.getParameter("status_fileName");
	String  oid_fieldName=request.getParameter("oid_fieldName");
	String  element_fieldName=request.getParameter("element_fieldName");
	String  status_fieldName=request.getParameter("status_fieldName");
	String factor = request.getParameter("factor");
	String selectedMetrics = request.getParameter("selectedMetrics");
	selectedMetrics=StringUtils.decodeSecurityChar(selectedMetrics);
	oid_fieldName=StringUtils.decodeSecurityChar(oid_fieldName);
	restdatafld=StringUtils.decodeSecurityChar(restdatafld);
	restParentNode=StringUtils.decodeSecurityChar(restParentNode);

	if(measure!=null && measure.length()>0)
	{
		measure=measure.replaceAll(" ","_bs_");
	}

	if (factor == null)
		factor="none";
	IniFile iniFile= EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_udtests.ini",true);
	
	if(fileName!=null && oid_fieldName!=null && !oid_fieldName.equals("") && !oid_fieldName.equals("null"))
	{
		String key=test+"#"+measure+":"+oid_fieldName;
		iniFile.setValue("TEST_MIBFILE_MAPPING",key,fileName);
		iniFile.saveFile();
	}
	if(element_fileName!=null && element_fieldName!=null && !element_fieldName.equals("") && !element_fieldName.equals("null"))
	{
		String key=test+":"+element_fieldName;
		iniFile.setValue("TEST_MIBFILE_MAPPING",key,element_fileName);
		iniFile.saveFile();
	}
	if(status_fileName!=null && status_fieldName!=null &&!status_fieldName.equals("") && !status_fieldName.equals("null"))
	{
		String key=test+":"+status_fieldName;
		iniFile.setValue("TEST_MIBFILE_MAPPING",key,status_fileName);
		iniFile.saveFile();
	}
	EgConfigFilesSync.releaseInstance(iniFile);
	String elementOid = request.getParameter("elementOid");
	String validOid = request.getParameter("validOid");
	String validValue = request.getParameter("validValue");
	String rediscPeriod = request.getParameter("rediscPeriod");
	String exceptionMsg = request.getParameter("alarmdescription");
	//UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();

	TestBean testBean = new TestBean(true);
	boolean isConfigTest = EgInstallInfo.isConfigTest(test);
	boolean isDescriptorBasedFlag = false;

	if(isConfigTest)
	{
		String isDecriptorBasedReq = request.getParameter("descVal");
		isDecriptorBasedReq=StringUtils.decodeSecurityChar(isDecriptorBasedReq);
		if(isDecriptorBasedReq != null)
		{
			isDecriptorBasedReq = isDecriptorBasedReq.trim();
			if(isDecriptorBasedReq.equalsIgnoreCase("true"))
			{
				 isDescriptorBasedFlag= true;
			}
		}
	}

	if(add.equals("add"))
	{
		if(testBean.doesMeasureExistFor(measure, test))
		{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			String msg = _mapping.getTextDescription("admin.ic.You are trying to add a measure/db column name which is already existing for this test")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please enter a new measure/db column name pair");
			rootJSON.put("AlertMsg",msg);

			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setValue("Description","Measures have not been configured for the test"+ " "+ test+ ". "+ "Measure or db column name is already existing for this test");
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
		}
		else if(testBean.doesIndexExist(test, index))
		{
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			String msg = _mapping.getTextDescription("admin.ic.You are trying to add an index which is already existing")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please select a new index value");
			rootJSON.put("AlertMsg",msg);

			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setCurrentValue("Measure Index",index);
			auditLogThread.setValue("Description","Measures have not been configured for the test"+ " "+ test +". "+"Measure index is already existing for this test");
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
		}
		else
		{
			/* code for auditlog starts */
			String myDbSize = "";
			if(dbSize != null && dbSize.equals("1"))
				myDbSize = "Number(7,4)";
			else if(dbSize != null && dbSize.equals("2"))
				myDbSize = "Number(20,4)";
			else if(dbSize != null && dbSize.equals("3"))
				myDbSize = "Number(16)";
			/* code for auditlog ends */

			String unit = null;
			if(unitA == null || unitA.length() == 0)
				unit = unitB;
			else
				unit = unitA;

			restdatafld=restParentNode+"|^|"+restdatafld;
			if(exceptionMsg != null && exceptionMsg.trim().length()>0)
			{
				testBean.addMeasureForTestWithAlarm(test, measure, dbSize, unit, process, factor, index, restdatafld,exceptionMsg);
				/* code for auditlog starts */

				auditLogThread.setCurrentValue("01~~Test name",test);
				auditLogThread.setCurrentValue("02~~Measure index",index);
				auditLogThread.setCurrentValue("03~~Measure name",measure);
				auditLogThread.setCurrentValue("04~~Database column size",myDbSize);
				auditLogThread.setCurrentValue("05~~Unit",unit);
				auditLogThread.setCurrentValue("06~~Process method",process);
				if(factor != null && factor.trim().length()>0 && !factor.equalsIgnoreCase("null") && !factor.equalsIgnoreCase("none"))
					auditLogThread.setCurrentValue("07~~Conversion Factor",(String)factorsMapping.get(factor));
				auditLogThread.setCurrentValue("08~~Alarm display string",exceptionMsg);
				auditLogThread.setCurrentValue("09~~REST Data Fields",restdatafld);
				/* code for auditlog ends */
			}
			else
			{
				testBean.addMeasureForTest(test, measure, dbSize, unit,	process, factor, index, restdatafld);
				/* code for auditlog starts */
				auditLogThread.setCurrentValue("01~~Test name",test);
				auditLogThread.setCurrentValue("02~~Measure index",index);
				auditLogThread.setCurrentValue("03~~Measure name",measure);
				auditLogThread.setCurrentValue("04~~Database column size",myDbSize);
				auditLogThread.setCurrentValue("05~~Unit",unit);
				auditLogThread.setCurrentValue("06~~Process method",process);
				if(factor != null && factor.trim().length()>0 && !factor.equalsIgnoreCase("null") && !factor.equalsIgnoreCase("none"))
					auditLogThread.setCurrentValue("07~~Conversion Factor",factor);
				auditLogThread.setCurrentValue("08~~REST Data Fields",restdatafld);
				/* code for auditlog ends */
			}
			String ur = "EgConfigRESTMeasureJson.jsp?" +"test=" + test + "&unit=" + "";
			/* code for auditlog starts */
			auditLogThread.setValue("Description","Measure " + measure + " has been added for the test " + test);
			auditLogThread.sendItToDB();
			/* code for auditlog ends */

			rootJSON.put("AlertType","Result");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
			rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been added successfully"));
			rootJSON.put("forwardPage",true);
			rootJSON.put("forwardURL",ur);
		}
	}
	else if(add.equals("del"))
	{
		testBean.deleteMeasure(test, measure);
		//new code for checking measure index using reviseMeasureIndex method written in TestBean
		testBean.reviseMeasureIndex(test);
		String ur = "EgConfigSnmpMeasureJson.jsp?" +"test=" + test + "&measure="+ "";
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Measure " + measure + " has been deleted from the test " + test);
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		rootJSON.put("AlertType","Result");
		rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
		rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been deleted successfully"));
		rootJSON.put("forwardURL",ur);
	}
	else if(add.equals("gen"))
	{
		if(!StringUtils.isNull(selectedMetrics))
		{
			ArrayList existingMeasureList = testBean.getMeasuresForTest(test);

			if(existingMeasureList!=null && !existingMeasureList.isEmpty())
			{
				Iterator itrMeas=existingMeasureList.iterator();
				while(itrMeas.hasNext())
				{
					String meas=(String)itrMeas.next();
					if(meas.indexOf(":")>0)
						meas=meas.substring(0,meas.indexOf(":"));

					testBean.deleteMeasure(test, meas);
					//new code for checking measure index using reviseMeasureIndex method written in TestBean
					testBean.reviseMeasureIndex(test);
				}
			}
			String defaultRESTDBSize="2";
			String defaultUnit="Number";
			String defaultProcessMethod="UNALTERED";
			String defaultConversionFactor="1";

			dbSize=defaultRESTDBSize;
			unitA=defaultUnit;
			process=defaultProcessMethod;
			factor=defaultConversionFactor;
			
			IniFile langIni = null;
			StringTokenizer stkMetcs=new StringTokenizer(selectedMetrics,",");
			int mIdx=1;
			while(stkMetcs.hasMoreTokens())
			{
				measure=stkMetcs.nextToken();

				if(measure!=null && measure.indexOf("|^|")>0)
				{
					restParentNode=measure.substring(measure.indexOf("|^|")+3);
					measure=measure.substring(0,measure.indexOf("|^|"));
				}
				if(measure!=null && measure.length()>0)
				{
					restdatafld=measure;
					measure=measure.replaceAll(" ","_bs_");
					if(langIni==null)
					{
						langIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_lang_"+trackerLanguage+".ini",true);
					}
				}
				if((restdatafld!=null && restdatafld.indexOf("_bs_")>-1) && langIni!=null)
				{
					String dispMeasName=restdatafld;
					dispMeasName=dispMeasName.replaceAll("_bs_"," ");
					langIni.setValue("MEASURE_NAME_MAPPING",test+":"+measure,dispMeasName);
					langIni.setValue("TEXT_NAME_MAPPING","admin.ic."+measure,dispMeasName);
				}
				index=""+mIdx;
				mIdx++;
				if(testBean.doesMeasureExistFor(measure, test))
				{
					continue;
				}
				else if(testBean.doesIndexExist(test, index))
				{
					continue;
				}
				else
				{
					restdatafld=measure;
					/* code for auditlog starts */
					String myDbSize = "";
					if(dbSize != null && dbSize.equals("1"))
						myDbSize = "Number(7,4)";
					else if(dbSize != null && dbSize.equals("2"))
						myDbSize = "Number(20,4)";
					else if(dbSize != null && dbSize.equals("3"))
						myDbSize = "Number(16)";
					/* code for auditlog ends */

					String unit = null;
					if(unitA == null || unitA.length() == 0)
						unit = unitB;
					else
						unit = unitA;

					restdatafld=restParentNode+"|^|"+restdatafld;
					if(exceptionMsg != null && exceptionMsg.trim().length()>0)
					{
						testBean.addMeasureForTestWithAlarm(test, measure, dbSize, unit, process, factor, index, restdatafld,exceptionMsg);
						/* code for auditlog starts */

						auditLogThread.setCurrentValue("01~~Test name",test);
						auditLogThread.setCurrentValue("02~~Measure index",index);
						auditLogThread.setCurrentValue("03~~Measure name",measure);
						auditLogThread.setCurrentValue("04~~Database column size",myDbSize);
						auditLogThread.setCurrentValue("05~~Unit",unit);
						auditLogThread.setCurrentValue("06~~Process method",process);
						if(factor != null && factor.trim().length()>0 && !factor.equalsIgnoreCase("null") && !factor.equalsIgnoreCase("none"))
							auditLogThread.setCurrentValue("07~~Conversion Factor",(String)factorsMapping.get(factor));
						auditLogThread.setCurrentValue("08~~Alarm display string",exceptionMsg);
						auditLogThread.setCurrentValue("09~~REST Data Fields",restdatafld);
						/* code for auditlog ends */
					}
					else
					{
						testBean.addMeasureForTest(test, measure, dbSize, unit,	process, factor, index, restdatafld);
						/* code for auditlog starts */
						auditLogThread.setCurrentValue("01~~Test name",test);
						auditLogThread.setCurrentValue("02~~Measure index",index);
						auditLogThread.setCurrentValue("03~~Measure name",measure);
						auditLogThread.setCurrentValue("04~~Database column size",myDbSize);
						auditLogThread.setCurrentValue("05~~Unit",unit);
						auditLogThread.setCurrentValue("06~~Process method",process);
						if(factor != null && factor.trim().length()>0 && !factor.equalsIgnoreCase("null") && !factor.equalsIgnoreCase("none"))
							auditLogThread.setCurrentValue("07~~Conversion Factor",factor);
						auditLogThread.setCurrentValue("08~~REST Data Fields",restdatafld);
						/* code for auditlog ends */
					}
				}
			}
			if(langIni!=null)
			{
				langIni.saveFile(true);
				EgConfigFilesSync.releaseInstance(langIni);
			}
		}
		
		/* code for auditlog starts */
		auditLogThread.setValue("Description","Measure " + measure + " has been added for the test " + test);
		auditLogThread.sendItToDB();
		/* code for auditlog ends */
		/*String ur = "EgConfigRESTMeasureJson.jsp?" +"test=" + test + "&unit=" + "";
		rootJSON.put("AlertType","Result");
		rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add Measure To Test"));
		rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measure has been added successfully"));
		rootJSON.put("forwardPage",true);
		rootJSON.put("forwardURL",ur);*/
		UpdateAndTransmitICInfo updateICInfo = new UpdateAndTransmitICInfo();
		testBean.deleteExistingTest(test);//added by James Thomas to remove records from measure_last and metatest tables for the given test if rows to the test exists.
		if(!testBean.checkIndices(test))
		{
			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setCurrentValue("Measure Index",index);
			auditLogThread.setValue("Description","Inconsistent measure indices for the test" +" "+ test);
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Generate a Test"));
			String msg = _mapping.getTextDescription("admin.ic.Inconsistent Measure Indices")+". ";
			msg += _mapping.getTextDescription("admin.ic.Please update the measure indices correctly");
			rootJSON.put("AlertMsg",msg);
		}
		else if(updateICInfo.getConnection())
		{
			/*if(elementOid != null && !elementOid.equals("") && rediscPeriod != null && !rediscPeriod.equals(""))
			{
				if(validOid == null || validOid.equals(""))
					validOid = "none";
				if(validValue == null || validValue.equals(""))
					validValue = "none";
				testBean.setSnmpOID(test, elementOid, validOid, validValue, rediscPeriod);
				testBean.setMultipleValue(test,"true");
			}
			else
			{
				testBean.setMultipleValue(test,"false");
			}*/
			String descriptorbasedtest=request.getParameter("descriptorbasedtest");
			descriptorbasedtest=StringUtils.decodeSecurityChar(descriptorbasedtest);
			String selDescRestFldVal=request.getParameter("selDescRestFldVal");
			selDescRestFldVal=StringUtils.decodeSecurityChar(selDescRestFldVal);
			if(!StringUtils.isNull(descriptorbasedtest))
			{
				if(!StringUtils.isNull(selDescRestFldVal))
				{
					if(selDescRestFldVal!=null && selDescRestFldVal.indexOf("|^|")>0)
					{
						restParentNode=selDescRestFldVal.substring(selDescRestFldVal.indexOf("|^|")+3);
						selDescRestFldVal=selDescRestFldVal.substring(0,selDescRestFldVal.indexOf("|^|"));
					}
					if(!StringUtils.isNull(restParentNode))
					{
						testBean.setRESTDataFieldForDescriptor(test,selDescRestFldVal,restParentNode);
					}
				}
			}
			String configuredMeasIntVals=request.getParameter("configuredMeasIntVals");
			if(!StringUtils.isNull(configuredMeasIntVals))
			{
				Hashtable measInternalValueMapping=new Hashtable();
				ArrayList measIntValConfigList=EgUtils.egTokenizer(configuredMeasIntVals,"!^!",false,false,false);
				Iterator itrmeasIntValConfList=measIntValConfigList.iterator();
				while (itrmeasIntValConfList.hasNext())
				{ 
					String keyVal=(String)itrmeasIntValConfList.next();
					ArrayList keyValList=EgUtils.egTokenizer(keyVal,"$!$",false,false,false);
					Iterator itrkeyValList=keyValList.iterator();
					while(itrkeyValList.hasNext())
					 {
						String key=(String)itrkeyValList.next();
						String value=(String)itrkeyValList.next();
						measInternalValueMapping.put(key,value);
					 }
				}
				if(measInternalValueMapping!=null && !measInternalValueMapping.isEmpty())
				{
					testBean.setRESTDataFieldMeasureInternalValue(test,measInternalValueMapping);
				}
			}
			testBean.setThresholds(test);
			EgThresholdInfo.setUpdated();
			String error = updateICInfo.setMeasures("REST",test);
			if(error != null && error.length() > 0)
			{
				/* code for auditlog starts */
				auditLogThread.setCurrentValue("Result","eG manager failed to create the required tables and indices for the new test");
				auditLogThread.setCurrentValue("Reason(s)","One or more database keywords are being used as test or measure names");
				auditLogThread.setCurrentValue("Reason(s)","The tablespace allocated to eG manager has no more space left to create tables");
				auditLogThread.setValue("Description","Error while generating test measures for the test" +" "+ test);
				auditLogThread.sendItToDB();
				/* code for auditlog ends */

				rootJSON.put("AlertType","Error");
				rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Generate a Test"));
				String msg = _mapping.getTextDescription("admin.ic.eG manager failed to create the required tables and indices for the new test")+". <br>";
				msg += _mapping.getTextDescription("admin.ic.Possible Reasons")+" :<br>";
				msg += "1) "+_mapping.getTextDescription("admin.ic.One or more database keywords are being used as test or measure names")+".<br>";
				msg += _mapping.getTextDescription("admin.ic.For Eg* \"varchar\", \"number\", \"offline\" e*t*c are database keywords")+". ";
				msg += _mapping.getTextDescription("admin.ic.One workaround is to use prefixes to existing test name/measure names")+". ";
				msg += _mapping.getTextDescription("admin.ic.Please change these  appropriately and try again")+". <br>";
				msg += "2) "+_mapping.getTextDescription("admin.ic.The tablespace allocated to eG manager has no more space left to create tables")+". ";
				msg += _mapping.getTextDescription("admin.ic.Please increase the tablespace size and try again")+". "+_mapping.getTextDescription("admin.ic.For more information you can check /manager/logs/error_log in the installation directory")+".";
				rootJSON.put("AlertMsg",msg);
			}
			else
			{
				String ur = "EgDefault.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
				if(!EgInstallInfo.isConfigTest(test))
				{
					//ur = "EgDefault.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
					ur = "EgDefaultJson.jsp?" + "t_name=" + test + "&server=null&qctr=0&page=true";
					rootJSON.put("forwardPage",true);
					rootJSON.put("forwardURL",ur);
				}
				else
				{
					rootJSON.put("AlertType","Result");
					rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Add new tests"));
					rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.The test has been generated successfully")+".");
					//rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Measures for")+" "+test+_mapping.getTextDescription("admin.ic.Your changes have been updated successfully"));
				}
				/* code for auditlog starts */
				auditLogThread.setValue("Description","Changes have been updated for the test" +" "+ test);
				auditLogThread.sendItToDB();
				/* code for auditlog ends */
			}
		}
		else
		{
			/* code for auditlog starts */
			auditLogThread.setCurrentValue("Test Name",test);
			auditLogThread.setCurrentValue("Measure Name",measure);
			auditLogThread.setValue("Description","Database connection failed"+". "+"Error while dealing with test measures for the test"+ test);
			auditLogThread.sendItToDB();
			/* code for auditlog ends */
			rootJSON.put("AlertType","Error");
			rootJSON.put("AlertTitle",_mapping.getTextDescription("admin.ic.Generate a Test"));
			rootJSON.put("AlertMsg",_mapping.getTextDescription("admin.ic.Database connection failed")+". "+_mapping.getTextDescription("admin.ic.Please check if the database is up and try again"));
		}
	}
	out.println(rootJSON);
%>






