<%
/*
 *		Name			:		EgConfigJmxMeasureJson.jsp
 *		Purpose			:		IC Test - JMX Type - Configure
 */
%>

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

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

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

	private String [] processes = {"UNALTERED",
					"PERCENT_INCREASE",
					"PERCENT_DECREASE",
					"PERCENT_CHANGE",
					"RATIO",
					"RATE",
					"DIFFERENCE"
						};
%>

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

	try
	{

	JSONObject rootJSON = new JSONObject();
	rootJSON.put("success","true");
	JSONObject hiddens = new JSONObject();
	JSONObject obj = new JSONObject();

	String helpuploadDir=EgInstallInfo.getInstallDir()+	"/manager/tomcat/webapps/final/eghelp";
	helpuploadDir=StringUtils.replace(helpuploadDir,"\\","/");
	IniFile iniUI = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	String factors [] = iniUI.getVariables("CONVERSION_FACTORS");
	Hashtable factorsMapping = new Hashtable();
	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);
		}
	}

	TestBean testBean = new TestBean(true);
	String test = request.getParameter("test");
	String mname = request.getParameter("measure");
	String dbsize = request.getParameter("dbsize");
	String unitValue = request.getParameter("unit");
	String otherUnitValue = request.getParameter("otherunit");
	String index = request.getParameter("index");
	String process = request.getParameter("process");
	String factor = request.getParameter("factor");
	String counter = request.getParameter("counter");
	String ctr = "";
	String dsnName = request.getParameter("dsnName");

	
	

	String scrollPosition = request.getParameter("position");
	scrollPosition = scrollPosition == null?"0":scrollPosition;

	//session.setAttribute("factorsMapping", factorsMapping);

	boolean isConfigTest = EgInstallInfo.isConfigTest(test);
	int iConfigFieldSize=new EgTesterInfo("manager").getConfigTestFieldSize(test);

	
	ArrayList measures = testBean.getMeasuresForTest(test);

	if(factor == null || factor.length() == 0 || factor.equals("null"))
		factor = "1";

	if(counter == null )
		counter = "";
	else
	{
		counter = counter.replace('*',' ');
		counter = counter.replace('|','%');
		counter = counter.trim();
	}

	String object = testBean.getObject(test);

	if(object == null)
		object = "";
//	if (domainName != null)
//		object = domainName;

	String instances = testBean.getInstances(test);
	if(instances == null )
		instances = "";

	String instances_neg = testBean.getInstancesNeg(test);
	if(instances_neg == null )
		instances_neg = "";
	ArrayList units = testBean.getAllUnits();
		Collections.sort(units);
	
	ArrayList measures_list = testBean.getMeasuresForTest(test);
	int i_mes_count = 0;
	if(measures_list != null)
	{
		i_mes_count = measures_list.size();
	}

	String size1 = "";
	String size2 = "";
	String size3 = "";
	String size4 = "";
	String size5 = "";

	if(mname == null || mname.length() == 0)
		mname = "";


	if(dbsize != null && dbsize.length() != 0)
	{
		if(dbsize.equals("1"))
			size1 = "selected";
		else if(dbsize.equals("2"))
			size2 = "selected";
		else if(dbsize.equals("3"))
			size3 = "selected";
	}

	String [] factorSel = new String[factors.length];
	for(int i=0; i<factorSel.length; i++)
	{
		if(iniUI.getValue("CONVERSION_FACTORS",(String)factors[i]).equals(factor))
			factorSel[i] = "selected";
		else
			factorSel[i] = "";
	}

	boolean isFactorEnabled = false;
	if(process == null)
	{
		isFactorEnabled = true;
	}
	else if(process.equals("UNALTERED") || process.equals("DIFFERENCE"))
	{
		isFactorEnabled = true;
	}
	String [] procSel = new String[processes.length];
	for(int i=0; i<procSel.length; i++)
	{
		if(processes[i].equals(process))
		{
			procSel[i] = "selected";
			
		}
		else
			procSel[i] = "";
	}

	Hashtable procVals = testBean.getProcesses(test);
	Hashtable factVals = testBean.getFactors(test);
	
	String restDSNName = testBean.getDSNName(test);
	
	rootJSON.put("restDSNName",restDSNName);
	boolean bDescriptorBasedTest=false;
	if(isConfigTest)
	{
		bDescriptorBasedTest=testBean.isThisDescriptorBasedTest(test);
	}

	if(measures == null || measures.size() == 0)
	{
		rootJSON.put("noMeasuresAdded",true);
	}
	else
	{
		rootJSON.put("noMeasuresAdded",false);
		String key = null;
		String value = null;
		String unit = null;
		String tmpInd = null;
		String alarm_msg = null;
		Integer idx;
		String temp = null;
		String procVal = null;
		String factVal = null;
		String org_factor = null;
		String org_measure = null;
		String org_process = null;
		String org_counter = null;
		String ctr1 = null;
		String ctr2 = null;
		String oldRESTDataField = null;
		String restdatafld = null;
		String tmpUnit = null;
		int ind = 0;
		int count = 0;
		JSONArray measureList = new JSONArray();
		JSONArray selectedRestFieldList = new JSONArray();
		String measureParentNode="";
		JSONObject restFldMap=new JSONObject();
		JSONArray restMeasureInternalMappingArr=new JSONArray();
		for(int i=0; i<measures.size(); i++)
		{
			obj = new JSONObject();
			temp = (String) measures.get(i);
			ind = temp.indexOf(":");
			if(ind < 0)
				continue;
			if(!isConfigTest)
			{
				key = temp.substring(0, ind);
				temp = temp.substring(ind+1);
				ind = temp.indexOf(":");
				if(ind < 0)
					continue;
				value = temp.substring(0, ind);
				temp = temp.substring(ind + 1);
				ind = temp.indexOf(":");
				if(ind < 0)
					continue;
				unit = temp.substring(0, ind);
				temp = temp.substring(ind + 1);
				//new code to effect alarm display string starts
				ind = temp.indexOf(":");
				if(ind < 0)
					continue;
				if(ind == 0)
				{
					alarm_msg = "";
					idx = new Integer(temp.substring(ind + 1));
				}
				else
				{
					alarm_msg = temp.substring(0, ind);//alarm msg
					idx = new Integer(temp.substring(ind + 1));
				}
				tmpInd = idx.toString();
				//new code to effect alarm display string ends
			}
			else
			{
				key = temp.substring(0, ind);       // measure name
				temp=temp.substring(ind+1);
				ind=temp.indexOf(":");
				if(ind < 0)
					continue;

				unit = temp.substring(0, ind);
				temp = temp.substring(ind + 1);

				idx = new Integer(temp.substring(0));
				tmpInd = idx.toString();
			}
			tmpUnit = "";

			if(unit.equals("%"))
			{
				tmpUnit = unit;
				for(int x=0;x<tmpUnit.length();x++)
				{
					if(tmpUnit.charAt(x) == '%')
						tmpUnit = tmpUnit.replace('%','|');
					else
						continue;
				}
			}
			else
			{
				tmpUnit = unit;
			}
			count++;

			if(procVals.containsKey(key))
				procVal = (String) procVals.get(key);

			if(factVals.containsKey(key))
				factVal = (String) factVals.get(key);

			ctr = testBean.getCounterOrOID(test,key,"counter");
			ctr1 = ctr;
			if(ctr1 != null && ctr1.length() > 0)
			{
				for(int x=0;x<ctr1.length();x++)
				{
					if(ctr1.charAt(x) == ' ')
						ctr1 = ctr1.replace(' ','*');
					else if(ctr1.charAt(x) == '%')
						ctr1 = ctr1.replace('%','|');
					else
						continue;
				}
			}
			restdatafld = testBean.getCounterOrOID(test,key,"restdatafld");
			String dataFieldParentNode=testBean.getRESTDataFldParentNode(test,restdatafld);
			
			measureParentNode=dataFieldParentNode;

			JSONArray restFldsArr=(JSONArray)restFldMap.get(measureParentNode);
			if(restFldsArr==null)
				restFldsArr=new JSONArray();

			restFldsArr.add(restdatafld);

			restFldMap.put(measureParentNode,restFldsArr);

			String s_tmpInd = "";
			if(alarm_msg != null)
				s_tmpInd = alarm_msg+":"+tmpInd;
			else
				s_tmpInd = tmpInd;

			if(!isConfigTest)
			{
				if(tmpUnit.equals("|"))
					org_measure = key+":"+value+":"+tmpUnit+":"+ s_tmpInd;
				else
					org_measure = key+":"+value+":"+unit+":"+ s_tmpInd;
			}
			else
			{
				if(tmpUnit.equals("|"))
					org_measure = key+":"+tmpUnit+":"+ s_tmpInd;
				else
					org_measure = key+":"+unit+":"+ s_tmpInd;
			}
			org_process = key+":"+procVal;
			org_factor = key+":"+factVal;
			org_counter = key+":"+ctr;
			oldRESTDataField = key+":"+restdatafld;
			ctr2 = org_counter;
			for(int x=0;x<ctr2.length();x++)
			{
				if(ctr2.charAt(x) == ' ')
					ctr2 = ctr2.replace(' ','*');
				else if(ctr2.charAt(x) == '%')
					ctr2 = ctr2.replace('%','|');
				else
					continue;
			}
			obj.put("measureIndex",tmpInd);
			String dispMeasNam=key;
			if(dispMeasNam!=null && dispMeasNam.indexOf("_bs_")>01)
			{
				dispMeasNam=StringUtils.replace(dispMeasNam,"_bs_"," ");
			}
			obj.put("measureName",_mapping.getTextDescription("admin.ic."+dispMeasNam));
			String alrmMsg = (alarm_msg!=null)?EgURLEncoder.encode(alarm_msg,"UTF-8"):"";
			
			String modifyURL = "EgModifyMeasuresJson.jsp?org_measure="+EgURLEncoder.encode(EgUIUtils.encodeSecurityChar(org_measure),"UTF-8")+"&org_process="+org_process+"&org_factor="+org_factor+"&org_counter="+ctr2+"&oldRESTDataColumn="+oldRESTDataField+"&test="+test+"&measure="+key+"&dbsize="+EgURLEncoder.encode(EgUIUtils.encodeSecurityChar(value),"UTF-8")+"&unit="+EgURLEncoder.encode(EgUIUtils.encodeSecurityChar(tmpUnit),"UTF-8")+"&index="+tmpInd+"&process="+procVal+"&factor="+factVal+"&counter="+ctr1+"&from=EgConfigRESTMeasure.jsp&alarmdescription="+alrmMsg+"&restdatafld="+restdatafld+"&dataFieldParentNode="+dataFieldParentNode;
			String deleteURL = "EgconfigrestmeasurepJson.jsp?add=del&test="+test+"&measure="+key;
			obj.put("modifyURL",modifyURL);
			obj.put("deleteURL",deleteURL);

			if(!isConfigTest)
			{
			//	String tempVal;
			//	tempVal = _mapping.getTextDescription("admin.ic."+value.substring(0,value.indexOf("(")));
			//	value=tempVal+value.substring(value.indexOf("("),value.length());
				obj.put("hideDatabaseColumnSize",false);
				obj.put("databaseColumnSize",value);
			}
			else
			{
				obj.put("hideDatabaseColumnSize",true);
			}
			obj.put("unit",unit);
			obj.put("processMethod",procVal);

			if(factVal != null && factVal.length() > 0 && !factVal.equals("none"))
			{
				obj.put("hideConversionFactor",false);
				obj.put("conversionFactor",factorsMapping.get(factVal).toString());
			}
			else
			{
				obj.put("hideConversionFactor",true);
			}
			if(!isConfigTest)
			{
				if((alarm_msg != null && alarm_msg.length()>0) )
				{
					obj.put("hideAlarmDispStr",false);
					obj.put("alarmDispString",alarm_msg);
				}
				else
				{
					obj.put("hideAlarmDispStr",true);
				}
			}
			obj.put("attributeName",ctr);
			obj.put("restdatafld",restdatafld);
			selectedRestFieldList.add(restdatafld);
			measureList.add(obj);
		}
		List descriptorConfigDetails=testBean.getRESTDescriptorParentNode(test);
		String descriptorNode="";
		String descriptorParentNode="";

		if(descriptorConfigDetails!=null && !descriptorConfigDetails.isEmpty())
		{
			descriptorNode=(String)descriptorConfigDetails.get(0);
			if(descriptorConfigDetails!=null && descriptorConfigDetails.size()>1)
			{
				descriptorParentNode=(String)descriptorConfigDetails.get(1);
			}
		}

		Hashtable restMeasaIntMappingHt=(Hashtable)testBean.getRESTMeasureInternalMapping(test);
		if(restMeasaIntMappingHt!=null && !restMeasaIntMappingHt.isEmpty())
		{
			HashMap measIntValMap=new HashMap();
			Iterator itrmeasIntMap=restMeasaIntMappingHt.entrySet().iterator();
			while(itrmeasIntMap.hasNext())
			{
				Map.Entry mp=(Map.Entry)itrmeasIntMap.next();
				if(mp!=null)
				{
					String measIntValKey=(String)mp.getKey();
					String measIntVal=(String)mp.getValue();
					String measNam="",measDispVal="";
					StringTokenizer stkMeasIntValKey=new StringTokenizer(measIntValKey,":");
					if(stkMeasIntValKey.hasMoreTokens())
					{
						stkMeasIntValKey.nextToken();
					}
					if(stkMeasIntValKey.hasMoreTokens())
					{
						measNam=stkMeasIntValKey.nextToken();
					}
					if(stkMeasIntValKey.hasMoreTokens())
					{
						measDispVal=stkMeasIntValKey.nextToken();
					}
					measIntValMap.put(measDispVal,measIntVal);
				//	JSONObject rowData=new JSONObject();
//					rowData.put("measure",measNam);
				//	rowData.put("key",measDispVal);
				//	rowData.put("value",measIntVal);
//					rowData.put("uniqueKey",measNam+":"+measDispVal);

				//restMeasureInternalMappingArr.add(rowData);
				}
			}
			if(measIntValMap!=null && !measIntValMap.isEmpty())
			{
				Iterator itrMeasIntValMap=measIntValMap.entrySet().iterator();
				while(itrMeasIntValMap.hasNext())
				{
					Map.Entry mp1=(Map.Entry)itrMeasIntValMap.next();
					String key1=(String)mp1.getKey();
					String val1=(String)mp1.getValue();
					JSONObject rowData=new JSONObject();
					rowData.put("key",key1);
					rowData.put("value",val1);
					restMeasureInternalMappingArr.add(rowData);
				}
			}
		}

		rootJSON.put("restFldMap",restFldMap);
		
		rootJSON.put("restMeasureInternalMappingArr",restMeasureInternalMappingArr);
		rootJSON.put("measureParentNode",measureParentNode);
		rootJSON.put("descriptorNode",descriptorNode);
		rootJSON.put("descriptorParentNode",descriptorParentNode);
		rootJSON.put("measuresList",measureList);
		rootJSON.put("selectedRestFieldList",selectedRestFieldList);
		rootJSON.put("selectedRestFieldList",selectedRestFieldList);
		rootJSON.put("domainName",object);
		rootJSON.put("mBeansIncluded",instances);
		rootJSON.put("mBeansExcluded",instances_neg);

		if(isConfigTest)
		{
			int ss=getConfigTestSizeIndex(iConfigFieldSize);
			JSONArray dbCols = new JSONArray();
			String[] dbColsDisp = new String[]{"32","64","128","256","512","1024"};
			String[] dbColsVal = new String[]{"1","2","3","4","5","6"};
			for (int i=0; i<dbColsDisp.length; i++)
			{
				obj = new JSONObject();
				obj.put("displayField",dbColsDisp[i]);
				obj.put("valueField",dbColsVal[i]);
				dbCols.add(obj);
			}
			rootJSON.put("dbColSizeList",dbCols);
			rootJSON.put("dbColSizeSelected",ss+"");
			rootJSON.put("descriptorBasedTestCheck",bDescriptorBasedTest?"checked":"");
		}
		hiddens.put("add","gen");
		hiddens.put("test",test);
	}
	hiddens.put("configtestflag",(isConfigTest?"true":""));

	rootJSON.put("measIndex",(++i_mes_count)+"");
	rootJSON.put("measNameValue",mname);

	if(!isConfigTest)
	{
		JSONArray dbCols = new JSONArray();
		String num = _mapping.getTextDescription("admin.ic.Number");
		String[] dbColsDisp = new String[]{num+"(20,4)",num+"(7,4)",num+"(16)"};
		String[] dbColsVal = new String[]{"2","1","3"};
		for (int i=0; i<dbColsDisp.length; i++)
		{
			obj = new JSONObject();
			obj.put("displayField",dbColsDisp[i]);
			obj.put("valueField",dbColsVal[i]);
			dbCols.add(obj);
		}
		rootJSON.put("dbColSizeList",dbCols);
		if (dbsize == null)
			dbsize = "2";
		rootJSON.put("dbColSizeSelected",dbsize);
	}
	if(unitValue == null || unitValue.length() == 0 || unitValue.equals("-1"))
	{
		JSONArray unitsArr = new JSONArray();
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Please select a unit"));
		obj.put("valueField","-1");
		unitsArr.add(obj);

		if(units != null && units.size() > 0)
		{
			for(int i=0; i<units.size(); i++)
			{
				String un = (String) units.get(i);
			//	if(un.equals("%"))
			//		continue;
				obj = new JSONObject();
				obj.put("displayField",un);
				obj.put("valueField",un);
				unitsArr.add(obj);
			}
		}
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Other"));
		obj.put("valueField","other");
		unitsArr.add(obj);
		rootJSON.put("unitsList",unitsArr);
		rootJSON.put("unitSelected","-1");
	}
	else if(!unitValue.equals("other") && !unitValue.equals("-1"))
	{
		JSONArray unitsArr = new JSONArray();
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Please select a unit"));
		obj.put("valueField","-1");
		unitsArr.add(obj);

		if(units != null && units.size() > 0)
		{
			for(int i=0; i<units.size(); i++)
			{
				String selected = "";
				String un = (String) units.get(i);
			//	if(un.equals("%"))
			//		continue;
				if(un.equals(unitValue))
				{
					rootJSON.put("unitSelected",un);
				}
				obj = new JSONObject();
				obj.put("displayField",un);
				obj.put("valueField",un);
				unitsArr.add(obj);
			}
		}
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Other"));
		obj.put("valueField","other");
		unitsArr.add(obj);
		rootJSON.put("unitsList",unitsArr);
	}
	else
	{
		JSONArray unitsArr = new JSONArray();
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Please select a unit"));
		obj.put("valueField","-1");
		unitsArr.add(obj);

		if(units != null && units.size() > 0)
		{
			for(int i=0; i<units.size(); i++)
			{
				String un = (String) units.get(i);
			//	if(un.equals("%"))
			//		continue;
				obj = new JSONObject();
				obj.put("displayField",un);
				obj.put("valueField",un);
				unitsArr.add(obj);
			}
		}
		obj = new JSONObject();
		obj.put("displayField",_mapping.getTextDescription("admin.ic.Other"));
		obj.put("valueField","other");
		unitsArr.add(obj);
		rootJSON.put("unitSelected","other");
		rootJSON.put("unitsList",unitsArr);
		rootJSON.put("showOtherTextBox",true);
		if (otherUnitValue != null && !otherUnitValue.equals(""))
			rootJSON.put("otherUnitValue",otherUnitValue);
	}

	JSONArray processArr = new JSONArray();
	rootJSON.put("selectedProcessMethod",processes[0]);
	for(int i=0; i<processes.length; i++)
	{
		String tmpProc = processes[i];
		String tmpSel = procSel[i];
		obj = new JSONObject();
		obj.put("displayField",tmpProc);
		obj.put("valueField",tmpProc);
		if (tmpSel.equals("selected"))
		{
			rootJSON.put("selectedProcessMethod",tmpProc);
		}
		processArr.add(obj);
	}
	rootJSON.put("processMethodList",processArr);

	if(isFactorEnabled)
	{
		rootJSON.put("hideConvFactor",false);
		JSONArray convFacts = new JSONArray();

		String tmpFact = "none";
		for(int i=0; i<factors.length; i++)
		{
			String fact = iniUI.getValue("CONVERSION_FACTORS", factors[i].toString());
			String tmpSel = factorSel[i];
			if(tmpSel.equals("selected"))
			{
				tmpFact = fact;
				rootJSON.put("convFactorSelected",fact);
			}
			obj = new JSONObject();
			obj.put("valueField",fact);
			obj.put("displayField",factors[i].toString());
			convFacts.add(obj);
		}
		rootJSON.put("convFactorList",convFacts);
		hiddens.put("factor",tmpFact);
	}
	else
	{
		rootJSON.put("hideConvFactor",true);
	}
	if(!isConfigTest)
	{
		rootJSON.put("hideAlarmDispStr",false);
		String alarmDisplay= request.getParameter("alarmDisplay");
		if (alarmDisplay == null)
		{
			alarmDisplay = "";
		}
		rootJSON.put("alarmDispStrValue",alarmDisplay);
	}
	rootJSON.put("mBeansListShow",false);
	
	hiddens.put("add","add");
	hiddens.put("test",test);
	rootJSON.put("hiddens",hiddens);
	out.println(rootJSON);

	}
	catch(Throwable t)
	{
		t.printStackTrace();
	}
%>


