<%
/*******************************************************************************
 *	File name       :	EgDispExtAgentsJson.jsp
 *  Purpose			:	To display the list of external agents in the system.
 ******************************************************************************/
%>

<%@ include file = "../../EgTrackerAJSON.jsp" %>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.EgSpecsInfo" %>
<%@ page import = "com.eg.EgURLEncoder" %>
<%@ page import = "com.eg.EgExternalInfo" %>
<%@ page import = "com.eg.EgServicesInfo" %>
<%@ page import = "com.egurkha.util.*" %>
<%@ page import = "com.egurkha.admin.ExternalAgent"%>
<%@ page import = "com.egurkha.IPComparator"%>
<%@ page language = "java" contentType = "text/html; charset=UTF-8" pageEncoding = "UTF-8" %>
<%@ page import = "net.sf.json.*"%>
<%@ page import= "egurkha.EgUIUtils"%>

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

<%
	JSONObject rootJson = new JSONObject();
	JSONObject screenLabels = new JSONObject();
	JSONArray gridExtAgents = new JSONArray();
	JSONObject gridObject = new JSONObject();

	//Limited admin
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	EgUuidInfo uuidInfo = new EgUuidInfo();
	EgCertUsage egCertUsage = new EgCertUsage();
	ArrayList usersList = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList != null && usersList.contains(_user.getLoginID()));
	EgExternalInfo extInfo = new EgExternalInfo("manager");
	String egTitleSearchStr = request.getParameter("egTitleSearchStr");
	if (egTitleSearchStr != null)
	{
		egTitleSearchStr = EgUIUtils.decodeSecurityChar(egTitleSearchStr);
	}
	boolean isSearchResult = (egTitleSearchStr!=null && egTitleSearchStr!="");
	ArrayList searchList = new ArrayList();
	if (isSearchResult)
	{
		StringTokenizer st = new StringTokenizer(egTitleSearchStr);
		while (st.hasMoreTokens())
		{
			String thisToken = st.nextToken().trim();
			if (thisToken.equals(""))
				continue;
			searchList.add(thisToken);
		}
	}
	screenLabels.put("admin.common.Modify",_mapping.getTextDescription("admin.common.Modify"));
%>

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

<%
	String selectedAgent = request.getParameter("selectedAgent");
	String hostIpForAgent= extInfo.getIpForAgent(selectedAgent);
	rootJson.put("hostIpForAgent",hostIpForAgent);
	EgUserElementsInfo userElmentsObj = new EgUserElementsInfo();
	EgSpecsInfo specs = new EgSpecsInfo("manager");
	trans.createFile("eg_external.ini");
	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 (!isLimitedAdmin)
	{
		agentsList = new ArrayList(Arrays.asList(s_eagents));
	}
	else
	{
		agentsList = userElmentsObj.getExternalAgentsForUser(user_name);
	}
	s_eagents = (agentsList != null) ? (String[])agentsList.toArray(new String[0]) : new String[0];

	IniFile iniObject = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_extmondash.ini",true);
	String[] zoneLocationVariable = trans.getVariables("Eg_External_Agents_Locations");

	Vector allInternalHosts = extInfo.getAllAgents();
	boolean isDisabled = false;
	if(s_eagents != null && s_eagents.length > 0)
	{
		Arrays.sort(s_eagents,String.CASE_INSENSITIVE_ORDER);
		List tmpList = new ArrayList();
		String defaultExtAgent = "";
		for (int j=0; j <s_eagents.length;j++)
		{
			String tmpExtagent = s_eagents[j];
			if (specs.getEGServer().equals(tmpExtagent))
			{
				defaultExtAgent = tmpExtagent;
			}
			else
			{
				tmpList.add(tmpExtagent);
			}
		}
		if(!defaultExtAgent.equals(""))
		{
			tmpList.add(0,defaultExtAgent);
		}

		EgServicesInfo serviceInfo = new EgServicesInfo("manager");
		ArrayList ipList = new ArrayList();
		ArrayList aList = new ArrayList();
		for (int x=0; x<tmpList.size(); x++)
		{
			String agentStr = (String) tmpList.get(x);
			if (serviceInfo.isIP(agentStr))
			{
				ipList.add(agentStr);
			}
			else
			{
				aList.add(agentStr);
			}
		}
		Collections.sort(ipList,new IPComparator());
		Collections.sort(aList, String.CASE_INSENSITIVE_ORDER);
		tmpList = new ArrayList();
		tmpList.addAll(ipList);
		tmpList.addAll(aList);

		s_eagents = (String[])tmpList.toArray(new String[0]);

		boolean searchItemFound = false;
		boolean emulationEnabled = false;

		JSONArray searchDispArr = new JSONArray();
		JSONObject searchDispObj = new JSONObject();
		ExternalAgent externAgnt = new ExternalAgent();

		for(int i=0;i < s_eagents.length;i++)
		{
			String hostIp = extInfo.getIpForAgent(s_eagents[i]);
			if (isSearchResult && !doesExist(searchList, s_eagents[i]+hostIp))
				continue;
			searchItemFound=true;
			searchDispObj.put("displayField",s_eagents[i]);
			searchDispObj.put("valueField",s_eagents[i]);
			searchDispArr.add(searchDispObj);

			gridObject.put("Hostname",s_eagents[i]);
			//String hostIp = extInfo.getIpForAgent(s_eagents[i]);
			gridObject.put("HostIP",hostIp);
			String zonelocation=iniObject.getValue("Eg_External_Agents_Locations",s_eagents[i]);
			gridObject.put("zoneLocation",zonelocation);

			if (EgInstallInfo.isClientEmulationEnabled)
			{
				if (!StringUtils.isNull(s_eagents[i]) && !s_eagents[i].equalsIgnoreCase("null"))
				{
					emulationEnabled = extInfo.isClientEmulationEnabled(s_eagents[i]);
				}
				if (emulationEnabled)
				{
					gridObject.put("Clientemulation","Yes");
				}
				else
				{
					gridObject.put("Clientemulation","No");
				}
			}
			boolean isUsed = externAgnt.checkIfAgentIsUsedForGrid(s_eagents[i]);
			gridObject.put("AssoDissAgnt",isUsed);
			boolean flagNotDel = false;

			if (allInternalHosts != null && allInternalHosts.contains(s_eagents[i]))
			{
				flagNotDel = true;
			}
			gridObject.put("internalAgent",flagNotDel);
			isDisabled = isUsed || flagNotDel;
			gridObject.put("isDisabled",isDisabled);
			gridExtAgents.add(gridObject);
		}
		rootJson.put("searchDispArr",searchDispArr);
	}
	else
	{
		rootJson.put("NoExtFound","true");
		screenLabels.put("admin.external.No external agents present in the system",_mapping.getTextDescription("admin.external.No external agents present in the system"));
	}
%>

<%!
	private boolean doesExist(List searchList, String thisGroup)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if (thisGroup.indexOf(nextStr)!=-1||(thisGroup.toUpperCase().indexOf(nextStr.toUpperCase()))!=-1)
				return true;
		}
		return false;
	}
%>
<%
	//if(request.getQueryString()!=null)
	//session.setAttribute("adminLastAccessedURL","/final/admin/EgExternalAgents.jsp?"+request.getQueryString());
	//else session.setAttribute("adminLastAccessedURL","/final/admin/EgExternalAgents.jsp");

	screenLabels.put("admin.common.No external agent(s) found for your current search",_mapping.getTextDescription("admin.common.No external agent(s) found for your current search"));
	rootJson.put("screenLabels",screenLabels);
	rootJson.put("gridExtAgents",gridExtAgents);


	String [] ex_var=null;
	if (isLimitedAdmin)
	{
		ArrayList agntsList = userElmentsObj.getExternalAgentsForUser(_user.getLoginID());
		ex_var = (String[])agntsList.toArray(new String[0]);
	}
	else
	{
		ex_var = trans.getVariables("Eg_External_Agents");
	}
	if (ex_var != null && ex_var.length > 0)
	{
		List ex_varList = Arrays.asList(ex_var);
		String strVarList = ex_varList.toString();
		strVarList = strVarList.substring(1,strVarList.length()-1);
		rootJson.put("exVarList",strVarList);
	}
	out.println(rootJson.toString());
%>



