<%
/**
 *	File name		:	EgConfigExtAgentsJson.jsp
 *	Purpose         :   To configure hosts to external agents. 
 */
%>

<%@ include file = "../../EgTrackerAJSON.jsp" %>
<%@ page import = "java.util.*"%>
<%@ page import = "com.eg.EgDiscInfo"%>
<%@ page import = "com.eg.EgRoleInfo"%>
<%@ page import = "net.sf.json.*"%>

<%@ 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);
	response.setContentType("application/json");
%>

<jsp:useBean id="trans" scope="page" class="egurkha.TransactionBean"/>

<%
	JSONObject rootJson = new JSONObject();
	JSONObject screenLabels = new JSONObject();

	//Limited admin
	EgRoleInfo roleInfo = EgRoleInfo.getInstance(sessionID,_user.getLoginID()); // For Limited admin
	//boolean isLimitedAdmin = !roleInfo.hasAllComponentAccess();
	EgCertUsage egCertUsage = new EgCertUsage();
	ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList.contains(_user.getLoginID()));

	EgExternalInfo externalInfo = new EgExternalInfo("manager");
	EgUuidInfo uuidInfo = new EgUuidInfo();

	screenLabels.put("admin.test.Please choose an external agent",_mapping.getTextDescription("admin.test.Please choose an external agent"));
	screenLabels.put("admin.test.External agent",_mapping.getTextDescription("admin.test.External agent"));
	screenLabels.put("admin.external.No managed hosts selected",_mapping.getTextDescription("admin.external.No managed hosts selected"));
	screenLabels.put("admin.external.No external agent hosts selected",_mapping.getTextDescription("admin.external.No external agent hosts selected"));
	screenLabels.put("admin.external.HOSTS MANAGED",_mapping.getTextDescription("admin.external.HOSTS MANAGED"));
	screenLabels.put("admin.external.HOSTS MANAGED BY THIS AGENT",_mapping.getTextDescription("admin.external.HOSTS MANAGED BY THIS AGENT"));
	screenLabels.put("admin.remote.Update",_mapping.getTextDescription("admin.remote.Update"));
	screenLabels.put("admin.external.HOSTS MANAGED BY OTHER EXTERNAL AGENTS",_mapping.getTextDescription("admin.external.HOSTS MANAGED BY OTHER EXTERNAL AGENTS"));
	screenLabels.put("admin.external.Please choose atleast one agent to manage or unmanage",_mapping.getTextDescription("admin.external.Please choose atleast one agent to manage or unmanage"));

	Vector v_managed_servers = new Vector();
	Vector v_eagent_servers = new Vector();	
	Vector v_othereagent_servers = new Vector();	

	String s_eagent = request.getParameter("eagent");
	String s_othereagent = request.getParameter("othereagent");
	String s_tmp = "";
	String s_val = "";
	s_eagent=(s_eagent==null)?"null":s_eagent;
	s_othereagent=(s_othereagent==null)?"null":s_othereagent;
	ArrayList managedEmulHosts = new ArrayList();
	if(s_eagent!=null && !s_eagent.equals("null"))
	{
		trans.createFile("eg_external.ini");
		String [] s_eagent_servers = trans.getVariables("Test_Mapping_Section");
		for(int i=0;i < s_eagent_servers.length;i++)
		{
			s_tmp = s_eagent_servers[i];
			s_val = trans.getStrValue("Test_Mapping_Section",s_tmp);
			if(s_val.indexOf(",") > -1 && (s_val.indexOf(","+s_eagent+",") > -1 || s_val.startsWith(s_eagent+",") || s_val.endsWith(","+s_eagent)))
			{
				v_eagent_servers.addElement(s_tmp);
			}
			else if(s_val.equals(s_eagent))
			{
				v_eagent_servers.addElement(s_tmp);
			}
			if(s_val.indexOf(",") > -1 && (s_val.indexOf(","+s_othereagent+",") > -1 || s_val.startsWith(s_othereagent+",") || s_val.endsWith(","+s_othereagent)))
			{
				v_othereagent_servers.addElement(s_tmp);
			}
			else if(s_val.equals(s_othereagent))
			{
				v_othereagent_servers.addElement(s_tmp);
			}
			else
			{
				continue;
			}
		}
		EgDiscInfo egdisc = new EgDiscInfo("manager");
		v_managed_servers = (s_othereagent!=null && !s_othereagent.equals("null")) ? v_othereagent_servers : egdisc.getAllHosts();

		for(int k=0; k<v_eagent_servers.size(); k++)
		{
			if(v_managed_servers.contains(v_eagent_servers.elementAt(k)))
			{
				v_managed_servers.removeElement(v_eagent_servers.elementAt(k));
			}
		}

		ArrayList rumCompType = new ArrayList();
		rumCompType.add("Real_user_monitor");
		ArrayList rumCompTobeRemovedFromExtAgent = egdisc.getAllHostsOfTypes(rumCompType); //List of RUM Components
		if (rumCompTobeRemovedFromExtAgent != null) {
			//Removing RUM Components from ManagedHostByThisAgent
			v_eagent_servers.removeAll(rumCompTobeRemovedFromExtAgent);
			//Removing RUM Components from ManagedHostByOthrAgnt
			v_managed_servers.removeAll(rumCompTobeRemovedFromExtAgent);
		}

		com.eg.EgTesterInfo testerInfo = new com.eg.EgTesterInfo("manager");
		if(!testerInfo.externalAgentRunsAllAggTests())
		{
			Hashtable ht = egdisc.getIpNickMap();
			if(ht != null && ht.containsKey("0.0.0.0"))
			{
				String nicks = (String)ht.get("0.0.0.0");
				String a_nick[] = com.egurkha.util.StringUtils.getTokens(nicks,":");
				List agg_nicks = Arrays.asList(a_nick);
				v_eagent_servers.removeAll(agg_nicks);
				v_managed_servers.removeAll(agg_nicks);
				nicks = null;
				a_nick = null;
				agg_nicks = null;
			}
		}

		// To show only emulater types hosts for emulation enabled external agents.
		boolean isEmulatedAgent = externalInfo.isClientEmulationEnabled(s_eagent);
		ArrayList emulTypes = externalInfo.getEmulatedTypes();
		managedEmulHosts = egdisc.getAllHostsOfTypes(emulTypes);
	//	if (isEmulatedAgent)  For Bug Id :20171
	//	{
	//		v_eagent_servers.retainAll(managedEmulHosts);
	//		v_managed_servers.retainAll(managedEmulHosts);
	//	}
		if (!isEmulatedAgent)
		{
			v_eagent_servers.removeAll(managedEmulHosts);
			v_managed_servers.removeAll(managedEmulHosts);
		}
	}

	String reqFrom = request.getParameter("from");
	reqFrom = (reqFrom != null)?reqFrom:"";

	JSONArray externalAgentsArray = new JSONArray();
	JSONArray otherExternalAgentsArray = new JSONArray();
	JSONObject externalValue = new JSONObject();
	JSONObject otherExternalValue = new JSONObject();

	externalValue.put("displayField","Choose an external agent");
	externalValue.put("valueField",-1);
	externalAgentsArray.add(externalValue);
	otherExternalValue.put("displayField","All");
	otherExternalValue.put("valueField","-1");
	otherExternalAgentsArray.add(otherExternalValue);

	trans.createFile("eg_external.ini");
	EgUserElementsInfo userElmentsObj = new EgUserElementsInfo();
	//String[] s_eagents = null;
	//if (isLimitedAdmin)
	//{
		//ArrayList agentsList = userElmentsObj.getExternalAgentsForUser(_user.getLoginID());
		//s_eagents = (String[])agentsList.toArray(new String[0]);
	//}
	//else
	//{
		//s_eagents = trans.getVariables("Eg_External_Agents");
	//}

	ArrayList compNicks = roleInfo.getAllServerNicks();
	String[] s_eagents = trans.getVariables("Eg_External_Agents");
	String user_name = _user.getLoginID();
	String dependent_OU_name = uuidInfo.getDirectDependentOU(user_name);
	ArrayList agentsList = new ArrayList();
	
	/* If the login user has limited admin access role and is a direct user of default organization (egenterprise),
	 * (or)
	 * If the login user has a full admin access role and is a super org,
	 * a. then show all external agents available in the manager if the user name is "admin".
	 * b. otherwise show its default organization' external agents along with default external agent.
	 */
	if ((uuidInfo.isUser(user_name) && dependent_OU_name.equalsIgnoreCase("egenterprise")) || (uuidInfo.isSuperOrg(user_name) && user_name.equalsIgnoreCase("egenterprise")))
	{
		if (user_name.equalsIgnoreCase("admin") && !isLimitedAdmin)
		{
			agentsList = new ArrayList(Arrays.asList(s_eagents));
		}
		else
		{
			agentsList = uuidInfo.getDefaultOrganizationAgentList("ExternalAgent");
			compNicks = getNicksAlone(uuidInfo.getDefaultOrganizationCompList());
		}
	}
	/* If the login user has limited admin access and is an sub organization or any user,
	 * then all of its own external agents will be shown at external agent UI.
	 */
	else if (isLimitedAdmin)
	{
		agentsList = userElmentsObj.getExternalAgentsForUser(user_name);
	}
	s_eagents = (agentsList != null) ? (String[])agentsList.toArray(new String[0]) : new String[0];
	IniFile externalIni = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_external.ini");
	Vector extAgentsVec = externalIni.getAllValues("Test_Mapping_Section");
	Set extAgentsList = new HashSet();
	if(extAgentsVec == null)
	{
		extAgentsVec = new Vector();
	}
	else
	{
		Iterator it = extAgentsVec.iterator();
		while(it.hasNext())
		{
			String extAgents =(String) it.next();
			StringTokenizer strToken = new StringTokenizer(extAgents,",");
			while(strToken.hasMoreTokens())
			{
				String tok = strToken.nextToken();
				extAgentsList.add(tok);
			}
		}
	}

	if(s_eagents != null)
	{
		Arrays.sort(s_eagents,String.CASE_INSENSITIVE_ORDER);
		ArrayList superHostList = externalInfo.getAllHostsOfExtAgent(s_eagent);
		for(int i=0;i < s_eagents.length;i++)
		{
			externalValue.put("displayField",s_eagents[i]);
			externalValue.put("valueField",s_eagents[i]);
			externalAgentsArray.add(externalValue);
			if (!s_eagents[i].equalsIgnoreCase(s_eagent))
			{
				if(extAgentsList.contains(s_eagents[i]))
				{
					ArrayList hostManagedBy = externalInfo.getAllHostsOfExtAgent(s_eagents[i]); //For Bug Id :20171
					ArrayList hostManagedBy1 =  new ArrayList(); //For Bug Id :20171
					hostManagedBy1 =(ArrayList) hostManagedBy.clone();
					if (!externalInfo.isClientEmulationEnabled(s_eagent) && externalInfo.isClientEmulationEnabled(s_eagents[i])) 
					{
						if(managedEmulHosts.size() > 0)
						{
							hostManagedBy.removeAll(managedEmulHosts);
							if(hostManagedBy.size() == 0)
							{
								continue;
							}
						}
					}
					if(superHostList.size() >0 )
					{
						hostManagedBy1.removeAll(superHostList);  //If all the host were managed by the external agent choosen then exclude the agentname from Host MAnged By dropdown
						if(hostManagedBy1.size() == 0 )
						{
							continue;
						}
					}
					//if (externalInfo.isClientEmulationEnabled(s_eagent) && externalInfo.isClientEmulationEnabled(s_eagents[i])) 
					//	{
					//		otherExternalValue.put("displayField",s_eagents[i]);
					//		otherExternalValue.put("valueField",s_eagents[i]);
					//		otherExternalAgentsArray.add(externalValue);
					//	}
					//	else if (!externalInfo.isClientEmulationEnabled(s_eagent) && !externalInfo.isClientEmulationEnabled(s_eagents[i]))
					//		{
					otherExternalValue.put("displayField",s_eagents[i]);
					otherExternalValue.put("valueField",s_eagents[i]);
					otherExternalAgentsArray.add(externalValue);
					//	}
				}
			}
		}
	}
	rootJson.put("externalAgentsArray",externalAgentsArray);
	rootJson.put("otherExternalAgentsArray",otherExternalAgentsArray);
	
	//ArrayList compNicks = roleInfo.getAllServerNicks();
	v_eagent_servers.retainAll(compNicks);
	v_managed_servers.retainAll(compNicks);

	JSONArray ManagedHostByThisAgnt = new JSONArray();
	JSONObject ManagedHostByThisAgntObj = new JSONObject();

	String existingAgents = "";
	if(v_eagent_servers.size() > 0)
	{
		Collections.sort(v_eagent_servers,String.CASE_INSENSITIVE_ORDER);
		for(int j=0;j < v_eagent_servers.size();j++)
		{
			String str_temp = (String) v_eagent_servers.elementAt(j);
			ManagedHostByThisAgntObj.put("displayField",str_temp);
			ManagedHostByThisAgntObj.put("valueField",str_temp);
			ManagedHostByThisAgnt.add(ManagedHostByThisAgntObj);

			existingAgents += str_temp + ",";
		}
		if(existingAgents.indexOf(",")!=-1)
		{
			existingAgents = existingAgents.substring(0,existingAgents.lastIndexOf(","));
			rootJson.put("existingAgents",existingAgents);
		}
	}
	rootJson.put("ManagedHostByThisAgent",ManagedHostByThisAgnt);

	JSONArray ManagedHostByOthrAgnt = new JSONArray();
	JSONObject ManagedHostByOthrAgntObj = new JSONObject();

	if(v_managed_servers.size() > 0)
	{
		Collections.sort(v_managed_servers,String.CASE_INSENSITIVE_ORDER);
		for(int x=0;x < v_managed_servers.size();x++)
		{
			ManagedHostByOthrAgntObj.put("displayField",v_managed_servers.elementAt(x));
			ManagedHostByOthrAgntObj.put("valueField",v_managed_servers.elementAt(x));
			ManagedHostByOthrAgnt.add(ManagedHostByOthrAgntObj);
		}
	}
	rootJson.put("ManagedHostByOthrAgnt",ManagedHostByOthrAgnt);
	rootJson.put("screenLabels",screenLabels);

	//if(request.getQueryString()!=null)
	//session.setAttribute("adminLastAccessedURL","/final/admin/EgExternalAgents.jsp?"+request.getQueryString()+"&fromAssignExt=true");
	//else session.setAttribute("adminLastAccessedURL","/final/admin/EgExternalAgents.jsp?eagent=null&fromAssignExt=true");

	v_eagent_servers.removeAllElements();
	v_managed_servers.removeAllElements();

	//System.out.println("rootJson______"+rootJson);
	out.println(rootJson.toString());
%>

<%!
	public ArrayList getNicksAlone(ArrayList compsList)
	{
		ArrayList resultNicksList = new ArrayList();
		if (compsList == null || compsList.size() == 0)
		{
			return resultNicksList;
		}
		for (int u=0; u<compsList.size(); u++)
		{
			String compNick = compsList.get(u).toString().trim();
			compNick = compNick.substring(compNick.indexOf(":")+1);
			compNick = compNick.substring(0,compNick.indexOf(":"));
			if (!resultNicksList.contains(compNick))
			{
				resultNicksList.add(compNick);
			}
		}
		return resultNicksList;
	}
%>



