<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@ page import="com.eg.supermanager.EgSmSuperInfo"%>
<%@ page import="com.eg.EgManagersInfo"%>
<%@ page import="com.eg.EgManager"%>
<%@ page import="com.eg.EgSmConfigInfo"%>
<%@ page import="java.util.*"%>
<%@ page import="com.egurkha.ini.IniUI"%>
<%@ page import="com.egurkha.util.DateUtil"%>
<%@ page import="net.sf.json.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%!
	private boolean doesExist(List searchList, String thisPolicy)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if (thisPolicy.indexOf(nextStr)!=-1||(thisPolicy.toUpperCase().indexOf(nextStr.toUpperCase()))!=-1)
				return true;
		}
		return false;
	}
%>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("text/html;charset=UTF-8");

	String operation = request.getParameter("operation");
	boolean addNewManager = operation != null && operation.equals("addNewManager");
	boolean modifyManager = operation != null && operation.equals("modifyManager");

	JSONObject rootJson = new JSONObject();
	EgSmSuperInfo superInfo = EgSmSuperInfo.getInstance();
	if(addNewManager)
	{
		List configList =(ArrayList)superInfo.getAllManagersId();
		if(configList != null && !configList.isEmpty())
		{
			JSONArray managerIds = new JSONArray();
			for(int i=0;i<configList.size();i++)
			{
				managerIds.add((String)configList.get(i));
			}
			rootJson.put("managerIds",managerIds);
		}
	}
	else if(modifyManager)
	{
		IniUI iniUi=IniUI.getInstance();
		EgManagersInfo mgrInfo =EgManagersInfo.getInstance();
		String managerId = request.getParameter("managerId");
		JSONObject screenLabels = new JSONObject();
		screenLabels.put("secondaryManagerTitle",_mapping.getTextDescription("admin.manager.Secondary Manager Information for")+" "+managerId);
		rootJson.put("screenLabels",screenLabels);
		Hashtable configMgrs=(Hashtable)mgrInfo.getConfiguredManagers();
		boolean isPrimaryManager = false;
		EgManager egManager = null;
		if(configMgrs != null && configMgrs.containsKey(managerId+EgSmConfigInfo.EG_HASH+"primary"))
		{
			isPrimaryManager = true;
			egManager=(EgManager)configMgrs.get(managerId+EgSmConfigInfo.EG_HASH+"primary");
		}
		EgManager smManager=(EgManager)superInfo.getManager(managerId);
		if(egManager != null)
		{
			if(!egManager.getURL().equals(smManager.getURL()))
			{
				egManager = smManager;
			}
		}
		else
		{
			egManager=smManager;
		}
		if(egManager != null)
		{
//			String displayIpHostname=egManager.getDisplayHost();//check here, why not hostname not coming for primary manager.
//			if(isPrimaryManager)
//			{
//				displayIpHostname = egManager.getIP();
//			}
			String lastReportTime=egManager.getLastReportedTime();
			String createdTime=superInfo.getValue("CREATED_TIME",managerId);
			String currentDateFormat = iniUi.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
			String dispDate ="None";
			if(createdTime != null && createdTime.length() > 0)
			{
				String time  = createdTime.substring(createdTime.indexOf(" ")+1);
				dispDate=DateUtil.changeDateFormat(createdTime,"MM/dd/yy",currentDateFormat)+" "+time;
			}
			if(lastReportTime != null && lastReportTime.length() > 0)
			{
				String time  = lastReportTime.substring(lastReportTime.indexOf(" ")+1);
				lastReportTime = DateUtil.changeDateFormat(lastReportTime,"MM/dd/yy",currentDateFormat)+" "+time;
			}
			else
			{
				lastReportTime="None";
			}
			JSONObject primaryManager = new JSONObject();
			primaryManager.put("primary_id",managerId);
//			primaryManager.put("primary_hostip",displayIpHostname);
//			primaryManager.put("primary_port",egManager.getPort());
//			primaryManager.put("primary_ssl",egManager.isSSL()?"true":"false");
			primaryManager.put("primary_url",egManager.getURL());
			String ALTURLS=superInfo.getValue(managerId,"ALTURLS");
			if(ALTURLS == null || ALTURLS.trim().length()==0 || ALTURLS.trim().equalsIgnoreCase("null"))
			{
				ALTURLS = "None";
			}
			primaryManager.put("primary_alturl",ALTURLS);
			primaryManager.put("primary_lastAccessedTime",lastReportTime);
			primaryManager.put("primary_createdTime",dispDate);
			rootJson.put("primaryManager",primaryManager);

			if(superInfo.isClusterExist(managerId))
			{
				String sec_mgr_key = managerId+EgSmConfigInfo.EG_HASH+"secondary";
				if(configMgrs.containsKey(sec_mgr_key))
				{
					EgManager clusterManager=(EgManager)configMgrs.get(sec_mgr_key);
					String url = "None";
					String natUrl = "None";
					String bothUrls=superInfo.getValue(managerId,"SECONDARY_URLS");
					if(bothUrls == null || bothUrls.trim().length()==0 || bothUrls.trim().equalsIgnoreCase("null"))
					{
						bothUrls = "None";
					}
					else
					{
						if(bothUrls.indexOf(",")>0)
						{
							url = bothUrls.substring(0,bothUrls.indexOf(","));
							natUrl = bothUrls.substring(bothUrls.indexOf(",")+1);
						}
						else
						{
							url = bothUrls;
						}
					}
					JSONArray superManagerArray = new JSONArray();
					JSONObject secondaryManager = new JSONObject();
					secondaryManager.put("secondary_url",url);
					secondaryManager.put("secondary_naturl",natUrl);
					secondaryManager.put("secondary_status",clusterManager.isRunning()?_mapping.getTextDescription("admin.common.Running"):_mapping.getTextDescription("admin.common.Not Running"));
					
					superManagerArray.add(secondaryManager);
					rootJson.put("secondaryManager",superManagerArray);
					rootJson.put("secondaryManagerFound",true);
				}
			}
		}
	}
	else
	{
		JSONArray managedManagersArray = new JSONArray();
		JSONArray unmanagedManagersArray = new JSONArray();
		EgManagersInfo mgrInfo =EgManagersInfo.getInstance();
		String searchStr=request.getParameter("egTitleSearchStr");
		String managedSearch=request.getParameter("managedSearch");
		String unmanagedSearchStr=request.getParameter("unmanagedSearch");

		boolean searchInManagedMgrs=(managedSearch!=null && managedSearch.equals("true"))?true:false;
		//boolean searchInUnmanagedMgrs=(unmanagedSearchStr!=null && unmanagedSearchStr.equals("true"))?true:false;
		searchStr=(searchStr!=null && searchStr.length() == 0)?null:searchStr;
		boolean isSearchResult =(searchStr!=null);
		ArrayList searchList = new ArrayList();

		int configCount=0;
		List configList =(ArrayList)superInfo.getAllManagersId();
		if (isSearchResult)
		{
			searchStr = egurkha.EgUIUtils.decodeSecurityChar(searchStr);
			StringTokenizer st = new StringTokenizer(searchStr);
			while (st.hasMoreTokens())
			{
				String thisToken = st.nextToken().trim();
				if (thisToken.equals(""))
					continue;
				searchList.add(thisToken);
			}
			List managedMgrs = superInfo.getManagedManagersId();
			List unmanagedList = superInfo.getUnmanagedManagersId();
			boolean managedManagersFound = false;
			//boolean unmanagedManagersFound = false;
			if(managedMgrs !=null && !managedMgrs.isEmpty())
			{
				managedManagersFound=true;
			}
//			if(unmanagedList !=null && !unmanagedList.isEmpty())
//			{
//				unmanagedManagersFound=true;
//			}
			rootJson.put("managedManagersFound",new Boolean(managedManagersFound));
//			rootJson.put("unmanagedManagersFound",new Boolean(unmanagedManagersFound));
			if(searchInManagedMgrs)
			{
				configList = superInfo.getManagedManagersId();
			}
//			else if(searchInUnmanagedMgrs)
//			{
//				configList = superInfo.getUnmanagedManagersId();
//			}
		}
		if(configList != null)
		{
			configCount = configList.size();
			Collections.sort(configList,String.CASE_INSENSITIVE_ORDER);
		}
		if(configCount > 0)
		{
			Vector dispVec=new Vector();
			for(int i=0; i<configList.size(); i++)
			{
				String configuredManagerId = (String)configList.get(i);
				if (isSearchResult )
				{
					if(!doesExist(searchList, configuredManagerId))
						continue;
					else
						dispVec.add(configuredManagerId);
				}
				else
					dispVec.add(configuredManagerId);
			}
			if(dispVec.size() > 0)
			{
				int managedCount = 0;
				Hashtable configMgrs=(Hashtable)mgrInfo.getConfiguredManagers();
				Collections.sort(dispVec,String.CASE_INSENSITIVE_ORDER);
				for(int i=0;i<dispVec.size();i++)
				{
					String configuredManagerId = (String)dispVec.get(i);
					if (isSearchResult && !doesExist(searchList, configuredManagerId)) continue;
					EgManager egManager=(EgManager)configMgrs.get(configuredManagerId+EgSmConfigInfo.EG_HASH+"primary");
					if(egManager == null)
						egManager=(EgManager)superInfo.getManager(configuredManagerId);
					if(egManager == null) continue;
					boolean running = egManager.isRunning();
//					String hostIp=egManager.getIP();
//					String port=egManager.getPort();
//					boolean ssl=egManager.isSSL();
//					String sslStr=ssl?"Yes":"No";
					boolean clusteredManager = superInfo.isClusterExist(configuredManagerId);
					String managerType = _mapping.getTextDescription("admin.manager.Standalone");
					if(clusteredManager)
					{
						if(running)
						{
							managerType = _mapping.getTextDescription("admin.manager.Redundant Cluster")+" (" + _mapping.getTextDescription("admin.manager.Primary") +")";
						}
						else
						{
							managerType = _mapping.getTextDescription("admin.manager.Redundant Cluster");
							EgManager s_manager = (EgManager)configMgrs.get(configuredManagerId+EgSmConfigInfo.EG_HASH+"secondary");
							if(s_manager != null)
							{
								if(!running)
								{
									running = s_manager.isRunning();
									if(running)
									{
										managerType = _mapping.getTextDescription("admin.manager.Redundant Cluster")+" (" + _mapping.getTextDescription("admin.manager.Secondary") +")";
									}
								}
							}
						}
					}
//					if(superInfo.isManaged(configuredManagerId))
//					{
//						JSONObject serviceObj = new JSONObject();
//						serviceObj.put("managerNickname",configuredManagerId);
//						serviceObj.put("managerType",managerType);
//						serviceObj.put("Status",running?"Running#Configured":"Not Running#Configured");
//						managedManagersArray.add(serviceObj);
//					}
//					else
//					{
//						JSONObject serviceObj = new JSONObject();
//						serviceObj.put("managerNickname",configuredManagerId);
//						serviceObj.put("managerType",managerType);
//						serviceObj.put("Status",running?"Running#Unconfigured":"Not Running#Unconfigured");
//						unmanagedManagersArray.add(serviceObj);
//					}
					JSONObject serviceObj = new JSONObject();
					serviceObj.put("managerNickname",configuredManagerId);
					serviceObj.put("managerType",managerType);
					if(superInfo.isManaged(configuredManagerId))
					{
						serviceObj.put("Status",running?"Running#Configured":"Not Running#Configured");
					}
					else
					{
						serviceObj.put("Status",running?"Running#Unconfigured":"Not Running#Unconfigured");
					}
					managedManagersArray.add(serviceObj);
				}
			}
		}
		session.setAttribute("adminLastAccessedURL","/final/admin/EgDispManagers.jsp");
		if(managedManagersArray.size()>0)
		{
			rootJson.put("managedManagersArray",managedManagersArray);
		}
	}
	out.println(rootJson.toString());
%>