<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import = "java.io.*"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.eg.EgConfigInfo"%>
<%@ page import = "com.eg.EgStartStopDisc"%>
<%@ page import = "com.eg.EgName"%>
<%@ page import="com.eg.EgURLEncoder"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.MappingNameSorter"%>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "com.eg.EgDiscInfo"%> 
<%@ page import = "com.eg.EgAggregateInfo"%>
<%@ page import = "com.eg.*"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%!
	EgConfigInfo Conf = new EgConfigInfo("manager");
	EgDiscInfo egDisc = new EgDiscInfo("manager");
	File f = new File (Conf.egDiscTrackingFile);
	EgStartStopDisc disc = EgStartStopDisc.getInstance();
	String s_disc_state =  "";
	String[] servers;
	String[] servertypes;
	String[] tmpUnmanServers;
	ArrayList unManagedList = new ArrayList();
	boolean b_isDiscAlive;
	private boolean isItemExists(List searchList, String server)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if (server.indexOf(nextStr)!= -1 || (server.toUpperCase().indexOf(nextStr.toUpperCase())) != -1)
			{
				return true;
			}
		}
		return false;
	}
%>

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

	JSONObject rootObj = new JSONObject();
	JSONObject errorObj = new JSONObject();
	JSONArray errArray = new JSONArray();

	egurkha.TestsNotConfigured tnCon = new egurkha.TestsNotConfigured();
	egurkha.ConfigBean menu = new egurkha.ConfigBean();
	int limit = 15;
	String strServer = request.getParameter("server");
	String autoRefresh=request.getParameter("autoRefresh");
	String activeCompTypes = request.getParameter("activeCompTypes");
	if (activeCompTypes == null)
	{
		activeCompTypes = "false";
	}

	String[] managedComponents = null;

	if (autoRefresh == null)
	{
		autoRefresh="true";
	}
	String strSearch = request.getParameter("strSearch");
	String strComponent = request.getParameter("strComponent");
	String tmpFrom = request.getParameter("from");
	String reqFrom = request.getParameter("reqfrom");
	if (reqFrom == null)
	{
		reqFrom = "navlink";
	}

	boolean isSearchResult = (strSearch != null && !strSearch.equalsIgnoreCase(""));
	ArrayList searchList = new ArrayList();
	if (isSearchResult)
	{
		StringTokenizer strTokens = new StringTokenizer(strSearch);
		while (strTokens.hasMoreTokens())
		{
			String thisToken = strTokens.nextToken().trim();
			if (thisToken.equals("")) continue;
			searchList.add(thisToken);
		}
	}

	IniFile egUI = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_ui.ini");
	String strLimit = egUI.getValue("MISC_ARGS","SEARCHBOX_ENABLE_LIMIT");
	if(strLimit != null)
	{
		limit = Integer.parseInt(strLimit);
	}
	String showOnly = request.getParameter("showOnly");
	if(strServer != null && strServer.startsWith("Agg_"))
	{
		showOnly = "aggregate_types";
	}

	if(showOnly == null || showOnly.trim().length()==0)
	{
		showOnly = "non_aggregate_types";
	}

	if(!EgInstallInfo.isAggregationSupported() && showOnly.equals("aggregate_types"))
	{
		rootObj.put("requestStatus","failed");
		errorObj.put("error1",_mapping.getTextDescription("admin.error.Your license does not allow you to use this feature"));
		errorObj.put("error2",_mapping.getTextDescription("admin.error.Please contact")+ " license@eginnovations.com");
	}

	Vector v = new Vector();
	v = tnCon.serversWithoutSID();
	int count = v.size();
	int k = 0;
	String strtemp = "";
	String strtemp1 = "";
	String strtemp2 = "";

	Vector manServers = new Vector();
	Vector unmanServers = new Vector();
	Vector newDiscServers = new Vector();

	String display = "admin.server.to manage/unmanage by systems";
	if(showOnly.equals("aggregate_types"))
	{
		display = "admin.server.to unmanage by systems";
	}

	String qryToAppend = "";
	if (tmpFrom != null && tmpFrom.equals("comp"))
	{
		qryToAppend += "&treeViewSrc=manageServer";
	}

	menu.createFile("eg_discover.ini");
	// User-Comp Mapping
	IniFile userCompMapIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_usercompmapping.ini");
	String userName = _user.getLoginID();
	EgRoleInfo ri = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	EgCertUsage egCertUsage = new EgCertUsage();
	EgUuidInfo uuidInfo = new EgUuidInfo();
	ArrayList allLimCompAccessUsers = egCertUsage.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (allLimCompAccessUsers != null && allLimCompAccessUsers.contains(userName));
	if (!isLimitedAdmin)
	{
		servertypes = menu.getServerTypes();
	}
	else //User-Comp Mapping
	{
		servertypes = ri.getServerTypes();
		ArrayList tempServList = new ArrayList(Arrays.asList(servertypes));
		tmpUnmanServers = userCompMapIni.getVariables(userName);
		if (tmpUnmanServers != null)
		{
			for (int h=0; h<tmpUnmanServers.length; h++)
			{
				String tmpServ = "";
				if(tmpUnmanServers[h].startsWith("#New"))
					tmpServ = tmpUnmanServers[h].substring(tmpUnmanServers[h].indexOf("#")+5,tmpUnmanServers[h].indexOf(":"));
				else if(tmpUnmanServers[h].startsWith("#Unmanage"))
					tmpServ = tmpUnmanServers[h].substring(tmpUnmanServers[h].indexOf("#")+10,tmpUnmanServers[h].indexOf(":"));
				else
					tmpServ = tmpUnmanServers[h].substring(0,tmpUnmanServers[h].indexOf(":"));
				if(!tempServList.contains(tmpServ))
					tempServList.add(tmpServ);
			}
		}
		servertypes = (String[])tempServList.toArray(new String[tempServList.size()]);
	}

	ArrayList a_server_types = new ArrayList();
	String [] s_arr = null;
	for(int z=0;z < servertypes.length;z++)
	{
		s_arr = menu.getVariables(servertypes[z]);
		if(s_arr.length > 1)
		{
			a_server_types.add(servertypes[z]);
		}
	}
	EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");
	Vector aggTypes = aggregateInfo.getAggregateTypes();
	if(aggTypes != null && !aggTypes.isEmpty())
	{
		if(showOnly.equals("aggregate_types"))
		{
			a_server_types.retainAll(aggTypes);
		}
		else
		{
			a_server_types.removeAll(aggTypes);
		}
	}
	else if(showOnly.equals("aggregate_types"))
	{
		a_server_types.clear();
	}
	aggTypes=null;
	aggregateInfo=null;
	//sorting starts
	ArrayList serverList = new ArrayList();
	String userLanguage = _user.getLanguage();
	IniUI  iniUI = IniUI.getInstance();
	if (userLanguage == null)
		userLanguage = iniUI.getDefaultLanguage();

	MappingNameSorter sorter = new MappingNameSorter(userLanguage);
	String s_tmp = "";
	for (int j=0; j<a_server_types.size(); j++)
	{
		s_tmp = (String)a_server_types.get(j);
		if(s_tmp.equals("Site_servers"))
		{
			continue;
		}
		serverList.add(s_tmp);
	}

	//Code starts to show managed component types only
	List tempList=new ArrayList();
	if(activeCompTypes!=null && activeCompTypes.equalsIgnoreCase("true"))
	{
		for(int j=0;j<serverList.size();j++)
		{
			String compType = (String)serverList.get(j);
		//	String[] tempCompNames = egDisc.getAllServersOfType(compType);
			String[] tempCompNames = ri.getAllServersOfType(compType);
			if(tempCompNames !=null && tempCompNames.length > 0)
			{
				tempList.add(compType);
			}
		}
		serverList = new ArrayList(tempList);
	}
	//Code ends

	JSONArray compArrayList = new JSONArray();
	serverList = sorter.getSortedCompTypeList(serverList);
	JSONObject componentList = new JSONObject();
	componentList.put("displayField",_mapping.getTextDescription("admin.server.Types of components"));
	componentList.put("valueField","-1");
	compArrayList.add(componentList);
	for(int i=0; i<serverList.size(); i++)
	{
		componentList = new JSONObject();
		EgName nameObj = (EgName)serverList.get(i);
		String tmpVal = nameObj.getActualName();
		String tmpDis = nameObj.getLocalName();
		componentList.put("displayField",tmpDis);
		componentList.put("valueField",tmpVal);
		compArrayList.add(componentList);
	}

	String activeCompCheck="";
	if(activeCompTypes !=null && activeCompTypes.equalsIgnoreCase("true"))
	{
		activeCompCheck="checked";
	}
	String label = "admin.server.Show managed component types only";
	if(showOnly.equals("aggregate_types"))
	{
		label = "admin.server.Show managed aggregate component types only";
	}

	if (strServer == null)
	{
		strServer = "-1";
	}

	// Show the search box only if the components count is > 15
	boolean isNeedManagedCompSearchBox = false;
	boolean isNeedUnManagedCompSearchBox = false;
	if (strServer != null)
	{
	//	managedComponents = egDisc.getAllServersOfType(strServer);
		managedComponents = ri.getAllServersOfType(strServer);
		isNeedManagedCompSearchBox = (managedComponents != null && managedComponents.length >= limit);
	}
	if (ri.hasAllComponentAccess())
	{
		servers = menu.getVariables(strServer);
	}
	else //User-Comp Mapping
	{
		ArrayList tmpFinalComps = new ArrayList();
		String[] tmpManServers = ri.getAllServersOfType(strServer);
		if (tmpManServers != null)
		{
			tmpFinalComps = new ArrayList(Arrays.asList(tmpManServers));
		}

		if (tmpUnmanServers != null)
		{
			for (int t=0; t<tmpUnmanServers.length; t++)
			{
				String tmpComp = tmpUnmanServers[t];
				String servName = tmpUnmanServers[t].substring(tmpUnmanServers[t].indexOf("|")+1,tmpUnmanServers[t].indexOf(":"));
				if (tmpComp.startsWith("#"))
				{
					if (strServer != null && servName.equalsIgnoreCase(strServer))
						tmpFinalComps.add(tmpComp);
				}
			}
		}
		servers = (String[])tmpFinalComps.toArray(new String[tmpFinalComps.size()]);
	}
	Arrays.sort(servers,String.CASE_INSENSITIVE_ORDER);
	for(int i=0; i<servers.length; i++)
	{
		if(servers[i].startsWith("#Unmanage|") || servers[i].startsWith("#New|"))
		{
			String s = servers[i].substring(servers[i].indexOf(":")+1);
			unManagedList.add(s);
			continue;
		}
	}
	isNeedUnManagedCompSearchBox = (unManagedList != null && unManagedList.size() >= limit);
	unManagedList = new ArrayList();

	//strServer = request.getParameter("server");
	//servers = menu.getVariables(strServer);
	String s_component = request.getParameter("s_component");
	if(s_component == null || s_component.indexOf(":")==-1)
	{
		s_component = "";
	}

	JSONArray managedCompArray = new JSONArray();
	Arrays.sort(servers,String.CASE_INSENSITIVE_ORDER);
	rootObj.put("isSearchNeededForFromField",new Boolean(false));
	rootObj.put("isSearchNeededForToField",new Boolean(false));
	for(int i=0; i<servers.length; i++)
	{
		JSONObject managedComponentList = new JSONObject();
		if(servers[i].startsWith("Format:"))
		{
			continue;
		}
		else if(servers[i].startsWith("#New|"))
		{
			String s = servers[i].substring(servers[i].indexOf(":")+1);
			newDiscServers.add(s);
			continue;
		}
		else if (servers[i].startsWith("#Unmanage|"))
		{
			String s = servers[i].substring(servers[i].indexOf(":")+1);
			unmanServers.add(s);
			continue;
		}
		else
		{
			manServers.add(servers[i]);
			servers[i] = servers[i].substring(servers[i].indexOf(":")+1);
			if (searchList !=null && searchList.size() > 0 && strComponent.equalsIgnoreCase("managed"))
			{
				if(isItemExists(searchList,Server.getServerNameWithoutPort(servers[i], false)))
				{
					managedComponentList.put("displayField",Server.getServerNameWithoutPort(servers[i], false));
					managedComponentList.put("valueField",servers[i]);
					managedCompArray.add(managedComponentList);
				}
			}
			else
			{
				managedComponentList.put("displayField",Server.getServerNameWithoutPort(servers[i], false));
				managedComponentList.put("valueField",servers[i]);
				managedCompArray.add(managedComponentList);
			}
		}
	}
	if (manServers.size() > 15)
	{
		rootObj.put("isSearchNeededForFromField",new Boolean(true));
	}

	if (unmanServers.size() > 15)
	{
		rootObj.put("isSearchNeededForToField",new Boolean(true));
	}

	session.setAttribute("managed",manServers); 
	session.setAttribute("unmanaged",unmanServers);
	session.setAttribute("newDiscSrvrs",newDiscServers);
	JSONArray unManagedCompArray = new JSONArray();
	Arrays.sort(servers,String.CASE_INSENSITIVE_ORDER);
	for(int i=0; i<servers.length; i++)
	{
		JSONObject unmanagedComponents = new JSONObject();
		if(servers[i].startsWith("#Unmanage|"))
		{
			servers[i] = servers[i].substring(servers[i].indexOf(":")+1);
			
			if (searchList != null && searchList.size() > 0 && strComponent.equalsIgnoreCase("unmanaged") )
			{
				if (isItemExists(searchList,Server.getServerNameWithoutPort(servers[i], false)))
				{
					unmanagedComponents.put("displayField",Server.getServerNameWithoutPort(servers[i], false));
					unmanagedComponents.put("valueField",servers[i]);
					unManagedCompArray.add(unmanagedComponents);
				}
			}
			else
			{
				unmanagedComponents.put("displayField",Server.getServerNameWithoutPort(servers[i], false));
				unmanagedComponents.put("valueField",servers[i]);
				unManagedCompArray.add(unmanagedComponents);
			}
		}

		if(servers[i].startsWith("#New|"))
		{
			servers[i] = servers[i].substring(servers[i].indexOf(":")+1);
			if (searchList != null && searchList.size() > 0 && strComponent.equalsIgnoreCase("unmanaged"))
			{
				if (isItemExists(searchList,Server.getServerNameWithoutPort(servers[i], false)))
				{
					unmanagedComponents.put("displayField",Server.getServerNameWithoutPort(servers[i], false));
					unmanagedComponents.put("valueField",servers[i]);
					unManagedCompArray.add(unmanagedComponents);
				}
			}
			else
			{
				unmanagedComponents.put("displayField","*"+Server.getServerNameWithoutPort(servers[i], false));
				unmanagedComponents.put("valueField",servers[i]);
				unManagedCompArray.add(unmanagedComponents);
			}
		}
	}

	String fromValue = request.getParameter("from");
	if (StringUtils.isNull(fromValue))
	{
		fromValue = "";
	}

	if (!rootObj.containsKey("requestStatus"))
	{
		rootObj.put("requestStatus","success");
	}
	rootObj.put("servers",compArrayList);
	rootObj.put("managedServers",managedCompArray);
	rootObj.put("unmanagedServers",unManagedCompArray);
	rootObj.put("errors",errorObj);
	if (strServer == null)
	{
		strServer = "-1";
	}
	//session.setAttribute("adminLastAccessedURL","/final/admin/EgConfigEnv.jsp?srvtype="+EgURLEncoder.encode(strServer,"UTF-8")+"&activeCompTypes="+activeCompTypes+"&reqfrom="+reqFrom);
	out.println(rootObj.toString());
%>




