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

<%@ include file = "../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.eg.EgExternalInfo"%>
<%@ page import = "com.eg.EgRoleInfo"%>
<%@ page import = "com.egurkha.util.*"%>
<%@ page import = "java.util.*"%>
<%@ 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();
	EgRoleInfo roleInfo = EgRoleInfo.getInstance(sessionID,_user.getLoginID()); // For Limited admin
	ArrayList compNicks = roleInfo.getAllServerNicks();
	//boolean isLimitedAdmin = !roleInfo.hasAllComponentAccess();
	EgCertUsage egCertUsage = new EgCertUsage();
	ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList.contains(_user.getLoginID()));

	screenLabels.put("admin.test.Please choose a remote agent",_mapping.getTextDescription("admin.test.Please choose a remote agent"));
	screenLabels.put("admin.test.Remote agent",_mapping.getTextDescription("admin.test.Remote agent"));
	screenLabels.put("admin.common.Updating",_mapping.getTextDescription("admin.common.Updating"));
	screenLabels.put("admin.remote.No managed hosts selected",_mapping.getTextDescription("admin.remote.No managed hosts selected"));
	screenLabels.put("admin.remote.Please choose atleast one agent to manage or unmanage",_mapping.getTextDescription("admin.remote.Please choose atleast one agent to manage or unmanage"));

	trans.createFile("eg_external.ini");
	EgUuidInfo uuidInfo = new EgUuidInfo();
	EgUserElementsInfo userElmentsObj = new EgUserElementsInfo();
	EgExternalInfo extInfo = new EgExternalInfo("manager");
	String[] s_eagent_servers = extInfo.getRemoteComponents();

	String[] s_eagents = trans.getVariables("Eg_Remote_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 remote agents available in the manager if the user name is "admin".
	 * b. otherwise show its default organization' remote agents along with default remote 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("RemoteAgent");
			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 remote agents will be shown at remote agent UI.
	 */
	else if (isLimitedAdmin)
	{
		agentsList = userElmentsObj.getRemoteAgentsForUser(user_name);
	}
	s_eagents = (agentsList != null) ? (String[])agentsList.toArray(new String[0]) : new String[0];

	Vector v_managed_servers = new Vector();
	List finalServers = new LinkedList();
	Vector v_eagent_servers = new Vector();
	Vector v_othereagent_servers = new Vector();
	String s_tmp = "";
	String s_val = "";
	String s_eagent = request.getParameter("eagent");
	String s_othereagent = request.getParameter("othereagent");
	s_eagent=(s_eagent==null)?"null":s_eagent;
	s_othereagent=(s_othereagent==null)?"null":s_othereagent;

	if(s_eagent != null && !s_eagent.equals("null"))
	{
		if (s_eagent_servers != null)
		{
			for(int i=0;i < s_eagent_servers.length;i++)
			{
				s_tmp = s_eagent_servers[i];
				s_val = extInfo.getRemoteAgentForHost(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;
				}
			}
		}
		v_eagent_servers.retainAll(compNicks);
		/* need to find out the servers which have agentless enabled */
		if (s_eagent != null && !s_eagent.equals("null"))
		{
			finalServers = v_othereagent_servers;
		}

		for(int k=0;k < v_eagent_servers.size();k++)
		{
			if(finalServers.contains(v_eagent_servers.elementAt(k)))
			{
				int index1 = finalServers.indexOf(v_eagent_servers.elementAt(k));
				finalServers.remove(index1);
			}
		}
		finalServers.retainAll(compNicks);
	}
	String reqFrom = request.getParameter("from");
	reqFrom = (reqFrom != null)?reqFrom:"";

	List v = new LinkedList();
	ArrayList al = new ArrayList();
	if (s_eagent_servers != null)
	{
		for (int a=0; a<s_eagent_servers.length; a++)
		{
			String info = extInfo.getAgentlessInfos(s_eagent_servers[a]);
			StringTokenizer tokenInfo = new StringTokenizer(info,",");
			int countTok = tokenInfo.countTokens();
			if (countTok == 5)
			{
				if (StringUtils.isNull(info) || (info.startsWith("None,") && info.endsWith(",None")))
				{
					v.add(s_eagent_servers[a]);
				}
			}
			if (countTok == 7)
			{
				while(tokenInfo.hasMoreElements())
				{
					al.add(tokenInfo.nextElement());
				}
				String firstEl = (String)al.get(0);
				String fifthEl = (String)al.get(4);
				if (StringUtils.isNull(firstEl) && StringUtils.isNull(fifthEl) || (firstEl.startsWith("None") && fifthEl.endsWith("None")))
				{
					v.add(s_eagent_servers[a]);
				}
				al.clear();
			}
		}
	}

	int count = v.size();
	rootJson.put("vector",v);

	screenLabels.put("admin.remote.The following components have not been configured for agentless monitoring",_mapping.getTextDescription("admin.remote.The following components have not been configured for agentless monitoring"));
	screenLabels.put("admin.remote.Immediately go to",_mapping.getTextDescription("admin.remote.Immediately go to"));
	screenLabels.put("admin.remote.ADD / MODIFY",_mapping.getTextDescription("admin.remote.ADD / MODIFY"));
	screenLabels.put("admin.remote.and configure the remote agents of these components",_mapping.getTextDescription("admin.remote.and configure the remote agents of these components"));
	screenLabels.put("admin.remote.HOSTS MANAGED",_mapping.getTextDescription("admin.remote.HOSTS MANAGED"));
	screenLabels.put("admin.remote.HOSTS MANAGED BY THIS AGENT",_mapping.getTextDescription("admin.remote.HOSTS MANAGED BY THIS AGENT"));

	//String[] s_eagents = null;
	//if (isLimitedAdmin)
	//{
		//EgUserElementsInfo userElmentsObj = new EgUserElementsInfo();
		//ArrayList agentsList = userElmentsObj.getRemoteAgentsForUser(_user.getLoginID());
		//s_eagents = (String[])agentsList.toArray(new String[0]);
	//}
	//else
	//{
		//s_eagents = extInfo.getAllRemoteAgents();
	//}


	if (s_eagents != null)
	{
		Arrays.sort(s_eagents,String.CASE_INSENSITIVE_ORDER);
	}
	else
	{
		s_eagents = new String[0];
	}

	if(s_eagents.length==0)
	{
		screenLabels.put("admin.remote.No Remote Agents currently available",_mapping.getTextDescription("admin.remote.No Remote Agents currently available"));
	}
	else
	{
		screenLabels.put("admin.remote.Remote agent",_mapping.getTextDescription("admin.remote.Remote agent"));

		JSONArray remoteAgentsArray = new JSONArray();
		JSONArray otherRemoteAgentsArray = new JSONArray();
		JSONObject remoteValue = new JSONObject();
		JSONObject otherRemoteValue = new JSONObject();

		remoteValue.put("displayField",_mapping.getTextDescription("admin.remote.Choose a remote agent"));
		remoteValue.put("valueField",-1);
		remoteAgentsArray.add(remoteValue);
		otherRemoteValue.put("displayField",_mapping.getTextDescription("admin.remote.Choose a remote agent"));
		otherRemoteValue.put("valueField",-1);
		otherRemoteAgentsArray.add(otherRemoteValue);
		IniFile externalIni = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_external.ini");
		Vector remAgentsVec = externalIni.getAllValues("Remote_Agent_Mapping_Section");
		if(remAgentsVec == null)
		{
			remAgentsVec = new Vector();
		}
		for(int i=0;i < s_eagents.length;i++)
		{
			if(s_eagents[i].equals(s_eagent))
			{
				remoteValue.put("displayField",s_eagents[i]);
				remoteValue.put("valueField",s_eagents[i]);
				remoteAgentsArray.add(remoteValue);
			}
			else
			{
				remoteValue.put("displayField",s_eagents[i]);
				remoteValue.put("valueField",s_eagents[i]);
				remoteAgentsArray.add(remoteValue);
				if (remAgentsVec.contains(s_eagents[i]))
				{
					remoteValue.put("displayField",s_eagents[i]);
					remoteValue.put("valueField",s_eagents[i]);
					otherRemoteAgentsArray.add(remoteValue);
				}
			}
		}
		rootJson.put("remoteAgentsArray",remoteAgentsArray);

		JSONArray ManagedHostByThisAgnt = new JSONArray();
		JSONObject ManagedHostByThisAgntObj = new JSONObject();
		rootJson.put("otherRemoteAgentsArray",otherRemoteAgentsArray);

		String existingAgents = "";
		int hostsCount = v_eagent_servers.size();
		if (hostsCount > 0)
		{
			Collections.sort(v_eagent_servers,String.CASE_INSENSITIVE_ORDER);
			for(int j=0; j<hostsCount; j++)
			{
				String str_temp = (String)v_eagent_servers.get(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);

		screenLabels.put("admin.thresdhold.Associate",_mapping.getTextDescription("admin.thresdhold.Associate"));
		screenLabels.put("admin.remote.OTHER HOSTS",_mapping.getTextDescription("admin.remote.OTHER HOSTS"));

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

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

		screenLabels.put("admin.remote.Update",_mapping.getTextDescription("admin.remote.Update"));
	}

	v_eagent_servers.removeAllElements();
	finalServers.clear();

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

	rootJson.put("screenLabels",screenLabels);
	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;
	}
%>



