<%@ include file="EgMonitorTracker.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>
<%@ page import = "com.eg.*"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import="com.eg.EgURLDecoder"%>
<%@ page import="com.egurkha.monitor.EgDiagnosisBean"%>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ page import = "com.egurkha.util.DateTimeTokenizer" %>
<%@ page import="net.sf.json.*"%>
<%@ taglib prefix="egui" uri="../WEB-INF/eg-taglib.tld" %>
<%@ 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);

	JSONObject json = new JSONObject();
	String isAgentBased = request.getParameter("isAgentBased");	
	String compType = request.getParameter("comptype");
	String layerName = request.getParameter("layername");
	String selectedTestName = request.getParameter("test");
	String port = request.getParameter("port");
	String agentIP = request.getParameter("agentIP");	
	String hostName = (String)session.getAttribute("HostNameForRC"); //Check  it whether it will be null	
	String msmt_host = (String)session.getAttribute("msmt_host");

	EgExternalInfo e = new EgExternalInfo("manager");
	String internalAgentHostName = e.getAgentFor(hostName,true);
	if(internalAgentHostName == null || internalAgentHostName.trim().length()==0 || internalAgentHostName.trim().equalsIgnoreCase("null"))
	{
		internalAgentHostName=hostName;
	}
	String agentOS = null;
	if("true".equals(isAgentBased))
	{	
		agentOS = AgentConfig.getAgentConfig().getAgentOS(internalAgentHostName);
	}
	else
	{
		String rmtOrExtAgentIp = request.getParameter("rmtOrExtAgentIp");
		if(!StringUtils.isNull(rmtOrExtAgentIp))
			agentOS = AgentConfig.getAgentConfig().getAgentOS(rmtOrExtAgentIp);
	}
	String activeSessions = request.getParameter("init_active_sessions_found");
	boolean activeSessionsFound = (activeSessions != null && activeSessions.equalsIgnoreCase("yes"))?true:false;
	//Hashtable userSessionMap = new Hashtable();
	//session.removeAttribute("userSessionMap");
	session.removeAttribute("deliveryGroupNames");
	session.removeAttribute("desktopDeliveryGroupNames");
	session.removeAttribute("DnsNames");
	session.removeAttribute("CtxLicenseTest_ddd");
	session.removeAttribute("ADUserNames");
	IniFile iniControls = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_controls.ini", true);
	IniFile iniUi = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini", false);
	Hashtable ht = null;
	String subject = null;
	String[] variables = null;
	String keyword = "_COMMANDS";
	String RCAkeyword = "_RCA_COMMANDS";//Specific to New RCA
	if(agentOS != null){
		if(agentOS.toLowerCase().indexOf("window") != -1){
			//subject = "WINDOWS"+keyword;
			Vector vars = iniUi.getVariables("WINDOWS_COMMANDS",true);
			Vector vals = iniUi.getAllValues("WINDOWS_COMMANDS");
			ht=new Hashtable();
			if(vars != null && vars.size()>0 && vals != null && vals.size()>0)
			{
				for(int i=0;i<vals.size();i++)
				{
					String key = (String)vars.get(i);
					String val = (String)vals.get(i);
					ht.put(key,val);
				}
			}
			subject = "WINDOWS"+RCAkeyword;
			vars = iniUi.getVariables(subject,true);
			vals = iniUi.getAllValues(subject);
			if(vars != null && vars.size()>0 && vals != null && vals.size()>0)
			{
				for(int i=0;i<vals.size();i++)
				{
					String key = (String)vars.get(i);
					String val = (String)vals.get(i);
					ht.put(key,val);
				}
			}
		}else{
			subject = agentOS.toUpperCase()+keyword;
		}
		if(subject != null){
			variables = iniUi.getVariables(subject);
		}
	}
	ArrayList alist = new ArrayList();
	JSONArray commandOpts = new JSONArray();
	JSONObject jOpt = new JSONObject();
	jOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol.Choose an action"));
	jOpt.put("valueField","-1");
	commandOpts.add(jOpt);
	JSONObject arguments = new JSONObject();
	if(ht != null && !ht.isEmpty())
	{
		ArrayList taskDispNames = new ArrayList(ht.keySet());
		Collections.sort(taskDispNames,String.CASE_INSENSITIVE_ORDER);
		Iterator itr = taskDispNames.iterator();
		while(itr.hasNext())
		{
			String key = (String)itr.next();
			String value= (String)ht.get(key);
			if(value != null && value.equalsIgnoreCase("Other") && !u_ser.getRCExecuteAllCommands())
			{
				continue;
			}
			if(value.equals("RC_15")|| (value.indexOf("gpupdate")>-1) || (value.indexOf("/flushdns")>-1) || value.trim().equalsIgnoreCase("netdom query fsmo"))
			{
				continue;
			}
			else if((value.equals("RC_31") || value.equals("RC_32") || value.equals("RC_33") || value.equals("RC_34") || value.equals("RC_35")))
			{
				continue;
			}
			else if(value.trim().equalsIgnoreCase("lodctr /r")  && !compType.equalsIgnoreCase("Windows_server"))
			{
				continue;
			}
			if(value!=null)
			{
				value = StringUtils.replace(value,"'","&&&");
				if(value.equalsIgnoreCase("ipconfig")){
					arguments.put(value,"/all");
				}
				else if(value.equalsIgnoreCase("ping") || value.equalsIgnoreCase("tracert")){
					arguments.put(value,"<<192.168.1.0>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("admin.dashboard.IP address"));
				}
				else if(value.equalsIgnoreCase("netstat")){
					arguments.put(value,"-an");
				}
				else if(value.equalsIgnoreCase("net")){
					arguments.put(value,"file");
				}
				else if(value.equalsIgnoreCase("net start") || value.equalsIgnoreCase("net stop")){
					arguments.put(value,"<<Service name>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.Service name"));
				}
				else if(value.equalsIgnoreCase("set")){
					arguments.put(value,"<<Variable>>");
				}
				else if(value.equalsIgnoreCase("dir")){
					arguments.put(value,"<<C:\\tmp>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.File path"));
				}
				else if(value.equalsIgnoreCase("RC_24")){
					arguments.put(value,"<<KB2600217>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.HotfixID"));
				}
				else if(value.startsWith("shutdown")){
					arguments.put(value,"/t 60");
				}
				else {
					arguments.put(value,"none");
				}
				value= value + ":OS";
				if(value != null && !value.equals("")){
					jOpt = new JSONObject();
					jOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol."+key));
					jOpt.put("valueField",value);
					jOpt.put("groupField",mappingInfo.getTextDescription("monitor.remotecontrol.OS"));
					commandOpts.add(jOpt);
				}
			}
		}
		if(commandOpts!=null && commandOpts.isEmpty())
		{
			JSONObject jOpt1 = new JSONObject();
			jOpt1.put("displayField",mappingInfo.getTextDescription("reporter.common.Not Applicable"));
			jOpt1.put("valueField","-1");
			commandOpts.add(jOpt1);
		}
	}
	else if(variables != null)
	{
		for(int inc=0; inc<variables.length;inc++)
		{
			String value = iniUi.getValue(subject,variables[inc]);
			
			if(value != null && value.equalsIgnoreCase("Other") && !u_ser.getRCExecuteAllCommands()){
				continue;
			}

			if(value.equals("RC_15")|| (value.indexOf("gpupdate")>-1) || (value.indexOf("/flushdns")>-1) || value.trim().equalsIgnoreCase("netdom query fsmo"))
			{
				continue;
			}
			else if((value.equals("RC_31") || value.equals("RC_32") || value.equals("RC_33") || value.equals("RC_34") || value.equals("RC_35")))
			{
				continue;
			}
			else if(value.trim().equalsIgnoreCase("lodctr /r")  && !compType.equalsIgnoreCase("Windows_server"))
			{
				continue;
			}
			if(value!=null){
				value = StringUtils.replace(value,"'","&&&");
				if(value.equalsIgnoreCase("ipconfig")){
					arguments.put(value,"/all");
				}
				else if(value.equalsIgnoreCase("ping") || value.equalsIgnoreCase("tracert")){
					arguments.put(value,"<<192.168.1.0>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("admin.dashboard.IP address"));
				}
				else if(value.equalsIgnoreCase("netstat")){
					arguments.put(value,"-an");
				}
				else if(value.equalsIgnoreCase("net")){
					arguments.put(value,"file");
				}
				else if(value.equalsIgnoreCase("net start") || value.equalsIgnoreCase("net stop")){
					arguments.put(value,"<<Service name>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.Service name"));
				}
				else if(value.equalsIgnoreCase("set")){
					arguments.put(value,"<<Variable>>");
				}
				else if(value.equalsIgnoreCase("dir")){
					arguments.put(value,"<<C:\\tmp>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.File path"));
				}
				else if(value.equalsIgnoreCase("RC_24")){
					arguments.put(value,"<<KB2600217>>");
					arguments.put(value+"_LABEL",mappingInfo.getTextDescription("monitor.remotecontrol.HotfixID"));
				}
				else if(value.startsWith("shutdown")){
					arguments.put(value,"/t 60");
				}
				else {
					arguments.put(value,"none");
				}
				value= value + ":OS";
				if(value != null && !value.equals("")){
					jOpt = new JSONObject();
					jOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol."+variables[inc]));
					jOpt.put("valueField",value);
					jOpt.put("groupField",mappingInfo.getTextDescription("monitor.remotecontrol.OS"));
					commandOpts.add(jOpt);
				}
			}
		}
		if(commandOpts!=null && commandOpts.isEmpty())
		{
			JSONObject jOpt1 = new JSONObject();
			jOpt1.put("displayField",mappingInfo.getTextDescription("reporter.common.Not Applicable"));
			jOpt1.put("valueField","-1");
			commandOpts.add(jOpt1);
		}
	}
	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	IniFile agentsIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini");
	HashMap grp_hm = new HashMap();
	variables = iniUi.getVariables("COMP_TYPE_TEST_NAME_RC");
	for(int j=0; j<variables.length;j++) {
		HashMap hm = new HashMap();
		String var = variables[j];
		String temp = var.substring(0,var.indexOf(":"));
	


		if(temp.equalsIgnoreCase(compType)){

			String testNameWithGroup = var.substring(var.indexOf(":") + 1);

			String gropName = "none";//Application
			String testName = "";

			if(testNameWithGroup != null && testNameWithGroup.indexOf("#") > -1){
				testName = testNameWithGroup.substring(0, testNameWithGroup.indexOf("#"));
				gropName = testNameWithGroup.substring(testNameWithGroup.indexOf("#") + 1);

			} else {
					testName = testNameWithGroup;
					gropName = compType;
			}
			// if the test is enabled for this component, allow remote control actions related to this test
			// if you execute remote control activities without enabling this test, if the parameters for the remote control activity are empty
			// or null, EgRemoteControlUtils class will throw NoSuchMethodException in agent side.
			boolean allowActivitiesForThisTest=false;
			String testKey = testName+"::"+hostName+":"+port;
			if(testName.equals("CitrixLicenseTest"))
			{
				testKey = testName+":Citrix_license_server:"+hostName+":"+port;
			}
			List agentNames = externalInfo.getAgentsFor(testName, compType, hostName);
			if(agentNames != null)
			{
				for(int i=0;i<agentNames.size();i++)
				{
					String tp = null;
					String agentName = (String) agentNames.get(i);
					String variables_agent[] = agentsIni.getVariables(agentName);
					for(int k=0; k<variables_agent.length; k++)
					{
						String tempKey = variables_agent[k];
						if(tempKey.equals(testKey))
						{
							tp = agentsIni.getValue(agentName, tempKey);
							break;
						}
					}
					if(tp != null && tp.trim().length()>0 && !tp.equalsIgnoreCase("null"))
					{
						allowActivitiesForThisTest=true;
						break;
					}
				}
			}
			if(!allowActivitiesForThisTest)
			{
				continue;
			}
			String mappedStr = iniUi.getValue("COMP_TYPE_TEST_NAME_RC",(var));
			if(mappedStr != null && (mappedStr=mappedStr.trim()).length()>0)
			{
				if(mappedStr.indexOf(",")>-1) {
					String array[] = StringUtils.getTokens(mappedStr,",");
					int size = array.length;
					for (int k=0; k<size; k++)
					{
						hm.put(array[k],testName);
					}
				}
				else {
					hm.put(mappedStr,testName);
				}
			}

			if(grp_hm != null && grp_hm.containsKey(gropName)){
			HashMap hmtemp = (HashMap)grp_hm.get(gropName);
				if(hm != null){
					hmtemp.putAll(hm);
					}
					grp_hm.put(gropName,hmtemp);

			} else {
				grp_hm.put(gropName,hm);
			}
		}
	}
	Set<String> groupKeys = grp_hm.keySet();
	Iterator itr = groupKeys.iterator();
	JSONObject actionOpt = new JSONObject();
	while(itr.hasNext())
	{
		String gruopKey = (String)itr.next();
		HashMap hm1 = (HashMap)grp_hm.get(gruopKey);
		alist = new ArrayList();

		
		String gruopKeyDispName = iniUi.getValue("RCA_GROUP_NAME_MAPPING", gruopKey);
		if(gruopKeyDispName == null || (gruopKeyDispName != null && gruopKeyDispName.trim().equals("")) ){
			gruopKeyDispName = mappingInfo.getComponentTypeDescription(compType);
		}
		
		Set<String> selectedRCs = hm1.keySet();
		subject="WINDOWS_COMMANDS_REMOTE_CONTROL";
		variables = iniUi.getVariables(subject);
		for(int i=0; i<variables.length;i++) {
			String var = variables[i];
			if(!selectedRCs.contains(var))
				continue;
			String value = iniUi.getValue(subject,var);
			//value = StringUtils.replace(value,"'","&&&");
			value = value + "#" + var+":"+hm1.get(var);
			alist.add(value);
		}
		Collections.sort(alist,String.CASE_INSENSITIVE_ORDER);
		
		if(alist != null)
		{
			for(int i=0; i<alist.size();i++) {
				String var = (String)alist.get(i);
				String rc = var.substring(var.indexOf("#")+1);
				String disp_rc = var.substring(0,var.indexOf("#"));

				actionOpt = new JSONObject();
				actionOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol."+disp_rc));
				actionOpt.put("valueField",rc);
				actionOpt.put("groupField", gruopKeyDispName);
				commandOpts.add(actionOpt);
			}
		}
	}
	JSONObject pageParams = new JSONObject();
	JSONObject screenLabels = new JSONObject();
	StringBuffer sbHiddenParams = new StringBuffer();
	screenLabels.put("monitor.remotecontrol.Arguments",mappingInfo.getTextDescription("monitor.remotecontrol.Arguments"));
	screenLabels.put("monitor.remotecontrol.Command syntax",mappingInfo.getTextDescription("monitor.remotecontrol.Command syntax"));
	screenLabels.put("monitor.remotecontrol.Output required",mappingInfo.getTextDescription("monitor.remotecontrol.Output required"));
	screenLabels.put("monitor.remotecontrol.Timeout",mappingInfo.getTextDescription("monitor.remotecontrol.Timeout")+" ("+mappingInfo.getTextDescription("monitor.remotecontrol.in sec")+")");
	screenLabels.put("monitor.remotecontrol.Execute",mappingInfo.getTextDescription("monitor.remotecontrol.Execute"));
	/**
	alist = new ArrayList();
	if(u_ser.getRCExecuteAllCommands())
	{
		subject = "CUSTOM_COMMANDS";
		variables = iniUi.getVariables("CUSTOM_COMMANDS");
		for(int i=0; i<variables.length;i++) {
			JSONObject jOpt1 = new JSONObject();
			String var = variables[i];
			String value = iniUi.getValue(subject,var);
			value = var + "#" + value;
			alist.add(value);
			
		}
	}**/
	json.put("arguments",arguments);
	pageParams.put("arguments","none");

	/**
	JSONArray customOpts = new JSONArray();
	subject = agentIP+"_CUSTOM_SCRIPTS";
	variables = iniUi.getVariables(subject);
	for(int i=0; i<variables.length;i++) {
		String var = variables[i];
		String value = iniUi.getValue(subject,var);
		value = var + "#" + value;
		alist.add(value);
	}
	Collections.sort(alist,String.CASE_INSENSITIVE_ORDER);
	actionOpt = new JSONObject();
	actionOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol.Choose a custom action"));
	actionOpt.put("valueField","-1");
	customOpts.add(actionOpt);
	if(alist != null)
	{
		for(int i=0; i<alist.size();i++) {
			String var = (String)alist.get(i);
			String rc = var.substring(var.indexOf("#")+1);
			String disp_rc = var.substring(0,var.indexOf("#"));

			actionOpt = new JSONObject();
			actionOpt.put("displayField",disp_rc);
			actionOpt.put("valueField",rc);
			actionOpt.put("groupField","Custom");
			commandOpts.add(actionOpt);
		}
	}
	**/

	String milliSec ="";
	String timeOut = null;
	synchronized(milliSec)
	{
		milliSec = System.currentTimeMillis() + "";
		Thread.currentThread().sleep(1);
	}
	sbHiddenParams.append("&txtTimeStamp="+String.valueOf(System.currentTimeMillis()));

	JSONArray yesNoOpts = new JSONArray();
	JSONObject yesOpt = new JSONObject();
	yesOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol.Yes"));
	yesOpt.put("valueField","Yes");
	yesNoOpts.add(yesOpt);

	JSONObject noOpt = new JSONObject();
	noOpt.put("displayField",mappingInfo.getTextDescription("monitor.remotecontrol.No"));
	noOpt.put("valueField","No");
	yesNoOpts.add(noOpt);

	json.put("yesNoOpts",yesNoOpts);
	pageParams.put("outputRequired","Yes");
	timeOut = iniControls.getValue("CONTROL_DEFAULTS","TimeOut");
	if(timeOut != null && timeOut.equals(""))
		timeOut = "60";
	pageParams.put("selectedTimeOutPeriod",String.valueOf(timeOut));
	
	if(sbHiddenParams!=null)
	{
		json.put("hiddenQStr",sbHiddenParams.toString());
	}
	json.put("screenLabels",screenLabels);
	pageParams.put("selectedCmd","-1");
	json.put("RemoteCmds",commandOpts);
	json.put("pageParams",pageParams);
	json.put("agentOS",agentOS);
	response.getWriter().write(json.toString());
%>




