<%@ include file="EgTrackerJSON.jsp" %>
<%@ page import = "com.egurkha.*" %>
<%@ page import = "com.egurkha.monitor.*" %>
<%@page import="com.eg.EgSpecsInfo"%>
<%@page import="com.eg.EgDbInfo"%>
<%@page import="egurkha.reporter.*"%>
<%@page import="egurkha.*"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@page import = "java.net.*"%>
<%@page import ="com.eg.EgTopoInfo"%>
<%@page import ="com.eg.EgDiscInfo"%>
<%@page import ="com.eg.EgTablesInfo"%>
<%@ page import = "com.eg.EgURLEncoder" %>
<%@page import ="egurkha.reporter.ErRemoteScriptingBean"%>
<%@page import ="com.egurkha.util.HtmlUtils"%>
<%@page import ="com.eg.EgMappingInfo"%>
<%@page import = "com.egurkha.util.StringUtils"%>
<%@page import = "com.egurkha.util.EgSorter"%>
<%@ page import="net.sf.json.*" %>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%
     response.setHeader("Cache-Control","no-store");
     response.setHeader("Pragma","no-cache");
     response.setDateHeader("Expires", -1);
%>
<% 
	JSONObject rootJSON = new JSONObject();
	JSONObject screenLabels = new JSONObject();
	JSONObject hiddenParams = new JSONObject();

	boolean isDouble = EgDbInfo.doubleByteEnabled;
	com.egurkha.ini.IniUI ui = (com.egurkha.ini.IniUI)com.egurkha.ini.IniUI.getInstance();
    User thisuser = UserRegistry.getInstance().getUser(session.getId());
   	String thisLanguage = ui.getDefaultLanguage();
	if (thisuser!=null)
	{
		String userLang = thisuser.getLanguage();
		if (userLang!=null && !userLang.equalsIgnoreCase("NULL"))
		{
			thisLanguage=userLang;
		}
	}
	String dashConfigFile = "eg_dashboardConfig.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile dashConfigIniFile = new IniFile(s_iniFile_dir + dashConfigFile);
	EgMappingInfo mappingInfo=new EgMappingInfo(thisLanguage);
	String loginid = thisuser.getLoginID();
	EgDiscInfo discInfo = new EgDiscInfo("manager");
	EgTopoInfo topoInfo = new EgTopoInfo("manager");
	EgSpecsInfo specsInfo = new EgSpecsInfo("manager");
	ErRemoteScriptingBean remote= new ErRemoteScriptingBean(loginid);
	EgTablesInfo tabinfo =new EgTablesInfo("manager");
	EgDbInfo dbInfo = new EgDbInfo("manager");
	ErInfo erInfo = new ErInfo(); 
	ErReportHelper erHelper = new ErReportHelper();
	String monHomePage=thisuser.getMonitorHomePage();
	String s_insightName = request.getParameter("view_name");
	if(s_insightName != null){
		s_insightName=com.egurkha.util.StringUtils.replace(s_insightName,"'","~#~");
		s_insightName=com.egurkha.util.StringUtils.replace(s_insightName,"&","|amp|");
	}
	String tier_position = request.getParameter("tier_position");
	String server_position = request.getParameter("server_position");
	String metric_position = request.getParameter("metric_position");

	int t_pos = Integer.parseInt(tier_position);
	int s_pos = Integer.parseInt(server_position);
	int m_pos = Integer.parseInt(metric_position);

	String s_site = request.getParameter("site_name");
	String s_test = request.getParameter("test_name");
	String s_info = request.getParameter("info_name");
	String s_measure = request.getParameter("measure_name");
	String s_metric = request.getParameter("metric_name");
	
	if(s_site!=null &&(s_site.length()==0 || s_site.equals("-1")))
		s_site = null;
	if(s_test!=null && (s_test.length()==0 || s_test.equals("-1")))
		s_test = null;

	String sessionID = session.getId();
	UserRegistry registry = UserRegistry.getInstance();
	User this_user = registry.getUser(sessionID);
	EgQInsightView insightView = this_user.getQInsightView(s_insightName);
	boolean isMetricUsed = insightView.isMetricUsed(t_pos-1,s_pos-1,m_pos-1);

	if((s_site == null || s_site.equalsIgnoreCase("null")) && (s_test==null || s_test.equalsIgnoreCase("null")) && isMetricUsed)
	{
		String arr_metricInfo[] = insightView.getMetricInfo(t_pos-1,s_pos-1,m_pos-1);
		s_site = arr_metricInfo[insightView.METRIC_SITE_IDX];
		s_test = arr_metricInfo[insightView.METRIC_TEST_IDX];
		s_info = arr_metricInfo[insightView.METRIC_INFO_IDX];
		int ind = s_info.indexOf("+");
		if(ind!=-1)
			s_info = s_info.substring(ind+1);
		s_measure = arr_metricInfo[insightView.METRIC_MEASURE_IDX];
		s_metric = arr_metricInfo[insightView.METRIC_NAME_IDX];
		rootJSON.put("isMetricUsed","true");
		rootJSON.put("selectedSiteCombo",s_site);
		rootJSON.put("selectedTestCombo",s_test);
		rootJSON.put("selectedInfoCombo",s_info);
		rootJSON.put("selectedMeasureCombo",s_measure);
	    s_metric=com.egurkha.util.StringUtils.replace(s_metric,"~#~","'");
		rootJSON.put("selectedMetricName",s_metric);		
	}

	String s_component = insightView.getServerInfo(t_pos-1,s_pos-1)[insightView.SERVER_COMP_IDX];
	
	StringTokenizer st = new StringTokenizer(s_component,":");
	String s_host = st.nextToken();
	String s_port = st.nextToken();
	String s_sid = null;
	if(st.countTokens()>1)
		s_sid = st.nextToken();
	String s_compTy = st.nextToken();
	String s_comp =s_host + ":" + s_port;


	Vector v_sites = null;
	if(discInfo.getSiteServers().contains(s_compTy))
	{
		ArrayList ar = topoInfo.getSitesForComponent(s_comp,s_compTy);
		if(ar!=null)
		{
			v_sites = new Vector(topoInfo.getSitesForComponent(s_comp,s_compTy));// returns all sites;
			v_sites.retainAll(this_user.getSites()); // preserve the user sites
		}
	}

	Vector v_tests = new Vector();	
	if(s_site==null || s_site.equals("") || s_site.equals("-1") || s_site.equalsIgnoreCase("null"))
	{		
		v_tests = erHelper.getMetaTestsForSite(null); 
		v_tests.remove("WebSiteTest");
		v_tests.remove("WebSiteTransactionTest");
		v_tests.retainAll(Arrays.asList(specsInfo.getTestsForServer(s_compTy)));
	}
	else 
	{				
		v_tests = erHelper.getMetaTestsForSite(s_site);		
	}
	
	//take only server relevant tests
	if(v_tests!=null && v_tests.size()>0)
	{
		String arr_tests[] = specsInfo.getTestsForServer(s_compTy);
		if(arr_tests!=null && arr_tests.length>0)
			v_tests.retainAll(Arrays.asList(arr_tests));
	}
	
	Vector v_measures = new Vector();
	Vector v_infos = new Vector();
	if(s_test!=null && !s_test.equals("-1"))
	{
		String site = s_site;
		if(site==null || site.trim().length()==0)	site = "NULL";
		
		String layer= "";
		ArrayList arry=new ArrayList();
		arry.addAll(tabinfo.getLayersForComponent(s_compTy));
		layer=tabinfo.getLayerForTest(s_test.trim());
		if(layer.indexOf(",")>-1)
		{
			 StringTokenizer stork=new StringTokenizer(layer,",");
			 while(stork.hasMoreTokens())
			 {
				   String tok=stork.nextToken();
					   if(arry.contains(tok))
						{
						
							layer=tok;
							break;
							
						}
			  }
		}
			 

		String componentin=s_component.substring(s_component.lastIndexOf(":")+1);
		if(specsInfo.isTestExternal(s_test))
		{	
			v_infos=new Vector();
			 String remot=remote.selectDescriptors(site,s_component,layer,s_test);
			 StringTokenizer strok=new StringTokenizer(remot,"*");
			 while(strok.hasMoreElements())
			 {
			  v_infos.add(strok.nextToken());
			   
			 }
			if(v_infos.contains("All"))
				v_infos.remove("All");
        }
		else
		{
			v_infos = erInfo.getInfosForTest(site,s_test,s_component);
			
		if(v_infos.size()==1 && ((String)v_infos.get(0)).equals("+"))
			v_infos = null;
		else
          v_infos = ErUtils.formatString(v_infos,"$0+$1","$1");
		}
		if(v_infos!=null && v_infos.contains("Not Applicable!"))
		    {
				v_infos.setSize(0);
            }
		if(v_infos!=null && v_infos.size()>0)
		{
			v_measures = new Vector(Arrays.asList(dbInfo.getMeasurementColumnsForTest(s_test)));
			for(int i=v_measures.size()-1;i>=0;i--)
			{
				String s_entry = (String)v_measures.get(i);
				if(s_entry.indexOf(":")!=-1)
					v_measures.remove(i);
			}
			Collections.sort(v_measures);
		}
	}

	String tierName = insightView.getTierName(t_pos-1);
	String serverName = insightView.getServerName(t_pos-1,s_pos-1);

	JSONObject siteCombo = new JSONObject();
	JSONArray siteArray = new JSONArray();
	
	if(v_sites == null)
	{
		rootJSON.put("site","false");
	}
	else
	{
		rootJSON.put("selectedSiteCombo","-1");
		siteCombo.put("displayField",mappingInfo.getTextDescription("monitor.quickinsight.Choose a site"));
		siteCombo.put("valueField","-1");
		siteArray.add(siteCombo);
		for(int i=0;i<v_sites.size();i++)
		{
			siteCombo.put("displayField",v_sites.get(i));
			siteCombo.put("valueField",v_sites.get(i));
			siteArray.add(siteCombo);
		}
		rootJSON.put("site","true");
	}

	JSONObject testCombo = new JSONObject();
	JSONArray testArray = new JSONArray();
	rootJSON.put("selectedTestCombo","-1");
	testCombo.put("displayField",mappingInfo.getTextDescription("monitor.quickinsight.Choose a test"));
	testCombo.put("valueField","-1");
	testArray.add(testCombo);
	
	for(int i=0;i<v_tests.size();i++)
	{
		String temptest =(String)v_tests.get(i);
		if(EgInstallInfo.isConfigTest(temptest))
		{
			v_tests.remove(temptest);
			i--;
		}
	}

	ArrayList hideList = new ArrayList();
	String hide_Test1[]= dashConfigIniFile.getVariables("Hide_Measures_UI");
	if(hide_Test1!=null && hide_Test1.length>0)
	{
		for(int k=0; k<hide_Test1.length; k++)
		{		
			String hide_TestVal1=(String)dashConfigIniFile.getValue("Hide_Measures_UI",hide_Test1[k]);
			if(hide_TestVal1!= null && hide_TestVal1.equalsIgnoreCase("All"))
				hideList.add(hide_Test1[k]);
		}
	}

	List testList = new ArrayList();
	Hashtable testNameHash = new Hashtable();

	if (v_tests!=null)
	{
		s_test = (s_test!=null)?s_test:"";
		for (int  i=0;i<v_tests.size();i++)
		{
			String testName = (String)v_tests.get(i);
			if(hideList != null && hideList.size()>0)
			{
				if(testName != null && !hideList.contains(testName)) 
				{
					testList.add(mappingInfo.getTestDescription(testName));
					testNameHash.put(mappingInfo.getTestDescription(testName),testName);
					if (testName.equals(s_test))
					{
						rootJSON.put("selectedTestCombo",testName);
					}				
				}
			}
			else if(hideList != null && hideList.size()==0)
			{
				testList.add(mappingInfo.getTestDescription(testName));
				testNameHash.put(mappingInfo.getTestDescription(testName),testName);
				if (testName.equals(s_test))
				{
					rootJSON.put("selectedTestCombo",testName);
				}		
			}
		}
	}
	//Sorting Test
	if (testList != null && testList.size() > 1)
	{
		EgSorter esort = new EgSorter(testList, 1);
		testList = esort.sort(1, "String", "asc");
	}
	if(testList != null && testList.size()>0 && testNameHash != null && testNameHash.size()>0) 
	{
		for(int c=0; c<testList.size(); c++)
		{
			String testDispName = (String)testList.get(c);
			if(testNameHash.containsKey(testDispName))
			{
				String valueField = (String)testNameHash.get(testDispName);						
				testCombo = new JSONObject();						
				testCombo.put("displayField",testDispName);
				testCombo.put("valueField",valueField);
				testArray.add(testCombo);
			}
		}			
	}	
	//code for combo change

	String descriptionText=request.getParameter("descriptionText");
	descriptionText=(descriptionText==null)?"Description":descriptionText;
	if(descriptionText.equals("-1"))
		descriptionText="Description";
	if(s_test!=null && !s_test.equals("null") && s_test.trim().length()>0)
	{
		descriptionText=s_test;
	}
	if(descriptionText.equalsIgnoreCase("Description"))
	{
		rootJSON.put("description","true");
		rootJSON.put("desc",mappingInfo.getTextDescription("monitor.common."+descriptionText));
	}
	else
	{
		rootJSON.put("description","false");
		Vector v_meas=erInfo.getInfosForTest(s_site,s_test,s_component);
		if(v_meas!=null && v_meas.size()>0)
		{
			rootJSON.put("testComboLabel",mappingInfo.getLabelDescription(descriptionText));
		}
		else
		{
			rootJSON.put("testComboLabel",mappingInfo.getTextDescription("monitor.common.Descriptor"));	
		}
	}
	JSONObject speciicTestCombo = new JSONObject();
	JSONArray speciicTestArray = new JSONArray();
	rootJSON.put("selectedSpecificTest","-1");
	speciicTestCombo.put("displayField",mappingInfo.getTextDescription("monitor.quickinsight.Choose a descriptor"));
	speciicTestCombo.put("valueField","-1");
	speciicTestArray.add(speciicTestCombo);
	

	if(v_infos == null || v_infos.isEmpty())
	{
		rootJSON.put("selectionValue",mappingInfo.getTextDescription("monitor.quickinsight.None"));
		rootJSON.put("showSelection","false");
	}
	else
	{
		rootJSON.put("showSelection","true");
		for(int i=0;i<v_infos.size();i++)
		{
			speciicTestCombo.put("displayField",v_infos.get(i));
			speciicTestCombo.put("valueField",v_infos.get(i));
			speciicTestArray.add(speciicTestCombo);
		}
	}

	JSONObject measureCombo = new JSONObject();
	JSONArray	measureArray = new JSONArray();
	rootJSON.put("selectedMeasure","-1");
	measureCombo.put("displayField",mappingInfo.getTextDescription("monitor.quickinsight.Choose a measure"));
	measureCombo.put("valueField","-1");
	measureArray.add(measureCombo);

	ArrayList hideMeasure = new ArrayList();
	String hide_Meas = dashConfigIniFile.getValue("Hide_Measures_UI",s_test);
	if(hide_Meas!= null && hide_Meas.trim().length() > 0 && !hide_Meas.equalsIgnoreCase("All"))
	{
		hideMeasure = com.egurkha.util.StringUtils.egTokenizer(hide_Meas, ",", false,true,false);
	}
	
	String measure="";
	s_measure = (s_measure!=null)?s_measure:"";
	if(v_measures!=null)
	{
		for (int i=0;i<v_measures.size();i++)
		{
			measure = (String)v_measures.get(i);
			s_test = (s_test!=null)?s_test:"";

			if(hideMeasure != null && hideMeasure.size()>0)
			{
				if(measure != null && !hideMeasure.contains(measure)) 
				{
					String selected = "";
					if (measure.equals(s_measure))
						rootJSON.put("selectedMeasure",measure);
					measureCombo.put("displayField",mappingInfo.getMeasureDescription(s_test,measure));
					measureCombo.put("valueField",measure);
					measureArray.add(measureCombo);
				}
			}
			else if(hideMeasure != null && hideMeasure.size()==0)
			{
				String selected = "";
				if (measure.equals(s_measure))
					rootJSON.put("selectedMeasure",measure);
				measureCombo.put("displayField",mappingInfo.getMeasureDescription(s_test,measure));
				measureCombo.put("valueField",measure);
				measureArray.add(measureCombo);
			}
		}
		rootJSON.put("metricName",mappingInfo.getMeasureDescription(s_test,com.egurkha.util.StringUtils.replace(s_measure,"~#~","'")));
	}

//ends here
	tierName=com.egurkha.util.StringUtils.replace(tierName,"~#~","'");
	serverName=com.egurkha.util.StringUtils.replace(serverName,"~#~","'");
	rootJSON.put("tierName",tierName);
	rootJSON.put("serverName",serverName);
	rootJSON.put("siteArray",siteArray);
	rootJSON.put("testArray",testArray);
	rootJSON.put("speciicTestArray",speciicTestArray);
	rootJSON.put("measureArray",measureArray);			

	out.println(rootJSON.toString());
%>
<%
	if(monHomePage!=null && monHomePage.trim().length()>0 && monHomePage.equals("Quick Insight"))
	{
		if(request.getQueryString()!=null)
		{
			session.setAttribute("monitorLastSession","/final/monitor/qinsight/EgQInsightHome.jsp?currentLoadingPage=EgQInsightMetric&"+request.getQueryString());
		}
		else
		{
			session.setAttribute("monitorLastSession","/final/monitor/qinsight/EgQInsightHome.jsp?currentLoadingPage=EgQInsightMetric");
		}
	}
%>