<%@ include file= "../../EgTrackerAJSON.jsp"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import="com.eg.EgDiscInfo"%>
<%@ page import="com.eg.EgGroupInfo"%>
<%@ page import="com.eg.EgURLEncoder"%>
<%@ page import="com.eg.EgInstallInfo"%>
<%@ page import="com.eg.EgAggregateInfo"%>
<%@ page import="egurkha.UserBean"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="java.util.*"%>
<%@ page import="com.eg.MappingNameSorter"%>
<%@ page import="com.eg.EgRoleInfo"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%!
	int allowed_count = 0;
	private boolean doesExist(List searchList, String compType)
	{
		Iterator i = searchList.iterator();
		while(i.hasNext())
		{
			String nextStr = (String) i.next();
			if(compType.indexOf(nextStr)!=-1||(compType.toUpperCase().indexOf(nextStr.toUpperCase()))!=-1)
				return true;
		}
		return false;
	}

	public void setMaxCount()
	{
		int count = 0;
		String NumberOfAgents="";//from License inforamtion
		String NumberOfBasicAgents="";
		String NumberOfExternalAgents="";
		String NoofApplications="";
		String NoofTargets="";
		String NotHavingValue="-";

		Hashtable ht = new Hashtable();
		UserBean user = new UserBean();

		String strCommand = EgInstallInfo.getInstallDir() + "/bin/viewCert" + " " + EgInstallInfo.getInstallDir() + "/bin/license";
		// the location of viewCert and the license file name
		ArrayList aListLicenseEntries=new ArrayList();
		String line;

		com.egurkha.util.EgUtilities egutil = com.egurkha.util.EgUtilities.createInstance();
		ArrayList al = egutil.getExecOutputLines(strCommand);
		if (al == null || al.size() < 2)
		{
			allowed_count = 0;
			return;
		}
		ArrayList bl = (ArrayList) al.get(0);
		if (bl == null || bl.size() == 0)
		{
			allowed_count = 0;
			return;
		}
		for (int r = 0; r<bl.size(); r++)
		{
			line = (String) bl.get(r);
			if(line.length()==0)
			{
				continue;
			}
			aListLicenseEntries.add(line);
		}

		//NewCode
		HashMap infoMap = new HashMap();
		for(int i=0; i<aListLicenseEntries.size(); i++)
		{
			String eleme = (String)aListLicenseEntries.get(i);
			int index = eleme.indexOf(":");
			if(index > 0)
			{
				String info=(eleme.substring(0,index)).trim();
				String value=eleme.substring(index+1);
				if(value.indexOf("Not Applicable") >= 0||(value.trim().startsWith("-")))
				{
					value = "-";
				}
				ht.put(info,value.trim());
			}
		}
		NumberOfAgents = (String)ht.get("No of Monitors");
		NumberOfBasicAgents = (String)ht.get("No of Basic Monitors");
		NoofApplications = (String)ht.get("No of Applications");
		NoofTargets= (String)ht.get("No of Monitored Targets");

		int available = 0;
		int numHosts = user.getBasicMonitorsCount() + user.getPremiumMonitorsCount(); // Total used agents

		if(NumberOfAgents.equals("-"))
		{
			//ht.put("Total Monitors",(NotHavingValue+"#"+numHosts+"#"+NotHavingValue+"#"+NotHavingValue));
		}
		else
		{
			String val1=cal(NumberOfAgents,numHosts);
			available = Integer.parseInt(NumberOfAgents) - numHosts;
			if(available < 0)
				available=0;
			//ht.put("Total Monitors",(NumberOfAgents+"#"+numHosts+"#"+available+"#"+val1));
		}
		//Its for Premium Monitors
		int availablePremiumLicence = 0;
		int used_Primium = user.getPremiumMonitorsCount();
		if(NumberOfAgents.equals("-")||NumberOfBasicAgents.equals("-"))
		{
			//ht.put("Premium Monitors",(NotHavingValue+"#"+used_Primium+"#"+NotHavingValue+"#"+NotHavingValue));
		}
		else
		{
			int premiumAllowed=0;
			String allow_Premium="-";
			String primi_percent ="-";
			if(Integer.parseInt(NumberOfAgents)>=Integer.parseInt(NumberOfBasicAgents))
			{
				premiumAllowed=Integer.parseInt(NumberOfAgents)-Integer.parseInt(NumberOfBasicAgents);
				allow_Premium=new Integer(premiumAllowed).toString();
				primi_percent=cal(allow_Premium,used_Primium);
				available = Integer.parseInt(allow_Premium) - used_Primium;
			}
			else
			{
				available = -1;
			}
			if(available < 0)
				available=0;
			availablePremiumLicence = available;
			//ht.put("Premium Monitors",(allow_Premium+"#"+used_Primium+"#"+available+"#"+primi_percent));
		}
		/* Get number of basic Monitors */
		int basic_used = user.getBasicMonitorsCount();
		if(NumberOfAgents.equals("-") || NumberOfBasicAgents.equals("-"))
		{
			//ht.put("Basic Monitors",(NotHavingValue+"#"+basic_used+"#"+NotHavingValue+"#"+NotHavingValue));
		}
		else
		{
			String basic_Percent=cal(NumberOfBasicAgents,basic_used);
			available = Integer.parseInt(NumberOfBasicAgents) - basic_used;
			if(available < 0)
				available=0;
			//ht.put("Basic Monitors",(NumberOfBasicAgents+"#"+basic_used+"#"+available+"#"+basic_Percent));
		}
		int numMonTargets = user.getManagedIpCount();
		if(!NoofTargets.equals("-"))
		{
			String val4=cal(NoofTargets,numMonTargets);
			available = Integer.parseInt(NoofTargets) - numMonTargets;
			if(available < 0)
				available=0;
			//ht.put("Monitored Targets",(NoofTargets+"#"+numMonTargets+"#"+available+"#"+val4));
		}

		/* Get number of applications being monitored */
		int numAppCount = user.getAppCount();
		if(!NoofApplications.equals("-"))
		{
			String val4=cal(NoofApplications,numAppCount);
			available = Integer.parseInt(NoofApplications) - numAppCount;
			if(available < 0)
				available=0;

			if(available>0 && availablePremiumLicence>0)
			{
				allowed_count = available;
			}
			else
				allowed_count = 0;

			//ht.put("Applications",(NoofApplications+"#"+numAppCount+"#"+available+"#"+val4));
		}
		else
		{
			allowed_count = -1;
		}
	}
	public String cal(String allow,double used)
	{
		String Total="";
		String allowasZero="-";
		try
		{
			if(allow.equals("-"))
			return "";
			double val=-5;
			double Total_agent=Double.parseDouble(allow);
			if(Total_agent>0)
			{
				val=(100*used)/Total_agent;
				if(val==0||val>100)
				{
					Total="-";
				}
				else
				{
					Total= new egurkha.reporter.ErUtils().round (val, 2);
				}
			}
			else
			{
				return allowasZero;
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
		return Total;
	}
	public String getCategoryForCompononetType(String compType)
	{
		IniFile iniFile = new IniFile(EgInstallInfo.getInstallDir() +"/manager/config/eg_infrastructure.ini");
		String[] subs = iniFile.getSubjects();
		String res ="";
		if(subs!=null)
		{
			for (int s=0; s<subs.length; s++)
			{
				String sub = subs[s];
				String[] vars = iniFile.getVariables(sub);
				if (vars!=null)
				{
					List compTypes = Arrays.asList(vars);
					if (compTypes.contains(compType))
					{
						res = sub;
					}
				}
			}
		}
		return res;
	}
%>
<%
try
{
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");

	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	List limitedAdminCompList=null;
	if(isLimitedAdmin)
	{
		limitedAdminCompList = _user.getServers(false);
	}
	EgGroupInfo groupInfo = new EgGroupInfo();
	EgAggregateInfo aggregateInfo = new EgAggregateInfo("manager");

	String operation = request.getParameter("operation");
	String elementType = (String)session.getAttribute("elementType");
	String name = (String)session.getAttribute("elementName");

	String indComponentTypes[] = null;
	ArrayList typeList = new ArrayList();
	if(!StringUtils.isNull(elementType) && !StringUtils.isNull(name))
	{
		typeList.addAll(groupInfo.getComponentTypes(elementType,name));
		Vector noAggSupportTypes = aggregateInfo.getNoAggregateSupportTypes();
		if(noAggSupportTypes !=null && !noAggSupportTypes.isEmpty())
		{
			typeList.removeAll(noAggSupportTypes);
		}
		for(int i=typeList.size()-1;i>=0;i--)
		{
			if(typeList.get(i).toString().startsWith("Agg_"))
				typeList.remove(i);
		}
		indComponentTypes = (String[]) typeList.toArray(new String[typeList.size()]);
	}
	if(indComponentTypes == null)
		indComponentTypes = new String[0];
	int indCount = indComponentTypes.length;

	String reqfrom = request.getParameter("reqfrom");
	String searchStr = request.getParameter("egTitleSearchStr");
	boolean isSearchResult = searchStr!=null && !searchStr.equals("");
	ArrayList siteServers = null;
	ArrayList searchList = null;
	Vector aggregateComponents = null;
	Hashtable aggTypeVsCompForElementName = null;
	Hashtable anchorTypeComponent = null;
	JSONObject rootJson = new JSONObject();
	if(indCount>0)
	{
		searchList = new ArrayList();
		aggTypeVsCompForElementName = new Hashtable();
		anchorTypeComponent = new Hashtable();
		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);
			}
		}
		reqfrom = (reqfrom == null ?"":reqfrom);
		siteServers = new EgDiscInfo("manager").getSiteServers();
		if(siteServers == null)
		{
			siteServers = new ArrayList();
		}
		IniFile egTests = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_tests.ini");
		String aggAgent = egTests.getValue("AGENTS_FOR_AGGREGATE_COMPONENTS","ExternalAgentRunsAllAggTests");
		if (aggAgent != null &&(aggAgent.equalsIgnoreCase("yes") || aggAgent.equalsIgnoreCase("true")))
		{
			allowed_count=-1;
		}
		else
		{
			setMaxCount();
		}
		rootJson.put("allowed_count",String.valueOf(allowed_count));
		String msg="";
		if(allowed_count==0)
		{
			com.eg.EgUsersInfo usersInfo = new com.eg.EgUsersInfo();
			boolean isNamedUsersCert = EgInstallInfo.isnamedUserLicense;
			msg = _mapping.getTextDescription("admin.error.You are exceeding the total/premium monitors permitted by your license")+"!";
			if (usersInfo.isUserBasedLicense())
			{
				msg += " "+_mapping.getTextDescription("admin.error.or")+" ";
				if (isNamedUsersCert)
				{
					msg += _mapping.getTextDescription("admin.error.You are exceeding the total number of named users permitted by your license")+"!";
				}
				else
				{
					msg += _mapping.getTextDescription("admin.error.You are exceeding the total number of concurrent users permitted by your license")+"!";
				}
			}
			msg += " "+_mapping.getTextDescription("admin.error.To upgrade your license to support additional components")+", ";
			msg += _mapping.getTextDescription("admin.error.please contact") +" <b>license@eginnovations.com</b>";
		}
		rootJson.put("allowed_count_0_msg",msg);
		String variables[] = aggregateInfo.getVariables("COMPONENT_ASSOCIATION");
		if(variables != null && variables.length>0)
		{
			for(int c=0;c<variables.length; c++)
			{
				if(variables[c].endsWith("#"+elementType+"#"+name))
				{
					String s = variables[c].substring(0,variables[c].indexOf("#"));
					if(isLimitedAdmin && limitedAdminCompList != null && !limitedAdminCompList.contains(s))
						continue;
					String type = s.substring(0,s.indexOf(":"));
					if(aggTypeVsCompForElementName.containsKey(type))
					{
						Vector alist = (Vector)aggTypeVsCompForElementName.get(type);
						alist.add(s);
					}
					else
					{
						Vector alist = new Vector();
						alist.add(s);
						aggTypeVsCompForElementName.put(type,alist);
					}
				}
			}
		}
		if(aggTypeVsCompForElementName != null && !aggTypeVsCompForElementName.isEmpty())
		{
			EgDiscInfo discInfo = new EgDiscInfo("manager");
			Iterator itr = aggTypeVsCompForElementName.keySet().iterator();
			while(itr.hasNext())
			{
				String thisType = (String)itr.next();
				String[] managedAggComps = discInfo.getAllServersOfType(thisType);
				if(managedAggComps != null && managedAggComps.length>0)
				{
					Object obj = aggTypeVsCompForElementName.get(thisType);
					if(obj != null && obj instanceof Vector)
					{
						ArrayList dList = new ArrayList();
						dList.addAll(Arrays.asList(managedAggComps));
						Vector alist = (Vector)obj;
						alist.retainAll(dList);
						if(alist.isEmpty())
						{
							aggTypeVsCompForElementName.remove(thisType);
						}
					}
				}
				else
				{
					aggTypeVsCompForElementName.remove(thisType);
				}
			}
		}
		//get all anchor components of all types, set for zonename/servicename/segmentname
		Hashtable anchorComponents = aggregateInfo.getAnchorComponentsOfElement(elementType, name);
		if(anchorComponents != null && !anchorComponents.isEmpty())
		{
			Iterator compItr = anchorComponents.keySet().iterator();
			while(compItr.hasNext())
			{
				String s = (String)compItr.next();
				String type = s.substring(0,s.indexOf(":"));
				anchorTypeComponent.put(type,s);
			}
		}
	}
	if(indCount > 0)
	{
		boolean showOnlyAnchorComponents = aggregateInfo.showOnlyAnchorComponents();
		boolean searchItemFound = false;
		String indComponentType="";
		List indServerTypeList = new ArrayList();
		for(int i=0;i<indCount;i++)
		{
			indComponentType = indComponentTypes[i];
			if(isSearchResult && !doesExist(searchList, _mapping.getComponentTypeDescription(indComponentType)))
				continue;
			indServerTypeList.add(indComponentType);
			searchItemFound=true;
		}
		if(searchItemFound)
		{
			JSONArray gridValuesArray = new JSONArray();
			String indServerTypes[] = (String[])indServerTypeList.toArray(new String[indServerTypeList.size()]);

			ArrayList serverList = new ArrayList(Arrays.asList(indServerTypes));
			MappingNameSorter sorter = new MappingNameSorter(trackerLanguage);
			serverList = sorter.getSortedCompTypeList(serverList);

			for(int i=0;i<serverList.size();i++)
			{
				EgName nameObj = (EgName)serverList.get(i);
				String compType = nameObj.getActualName();
				String aggCompType = "Agg_"+compType;
				String category = getCategoryForCompononetType(compType);
				if(compType.endsWith("_ex"))
				{
					category = "CUSTOM_COMPONENTS";
				}
				JSONObject gridRowValues = new JSONObject();
				gridRowValues.put("componentType",_mapping.getComponentTypeDescription(aggCompType));
				gridRowValues.put("agg_type",aggCompType);

				String anchorComp = null;
				String anchorCompNick = null;
				if(anchorTypeComponent != null && anchorTypeComponent.containsKey(aggCompType))
				{
					anchorComp = (String)anchorTypeComponent.remove(aggCompType);
					anchorCompNick = anchorComp.substring(anchorComp.indexOf(":")+1,anchorComp.lastIndexOf(":"));
				}
				if(showOnlyAnchorComponents)
				{
					if(anchorComp != null)
					{
						aggregateComponents = new Vector();
						aggregateComponents.add(anchorComp);

					}
					else
					{
						aggregateComponents = new Vector();
					}
				}
				else
				{
					if(aggTypeVsCompForElementName.containsKey(aggCompType))
					{
						aggregateComponents = (Vector)aggTypeVsCompForElementName.remove(aggCompType);
						if(aggregateComponents.contains(anchorComp))
						{
							Collections.sort(aggregateComponents,String.CASE_INSENSITIVE_ORDER);
							aggregateComponents.remove(anchorComp);
							aggregateComponents.add(0,anchorComp);
						}
					}
					else
					{
						aggregateComponents = new Vector();
					}
				}
				boolean isElementZone = elementType.equalsIgnoreCase("zone");
				int componentCount = aggregateComponents.size();
				if(componentCount>0)
				{
					String tmpStr = "<div style='margin-left:50px'><table class='mylink' cellspacing=\"0\" cellpadding=\"4\" border=\"0\" width=\"90%\" align=\"left\"><tr>";
					if(aggregateComponents != null && aggregateComponents.size() > 0)
					{
						int countColumn = 0;
						for (int j = 0;j<aggregateComponents.size();j++)
						{
							String aggComp = (String)aggregateComponents.get(j);
							String autoAssociatedToZone = isElementZone && groupInfo.doesComponentExistUnderZone(name, aggComp) ?"yes":"no";
							String nickPort = aggComp.substring(aggComp.indexOf(":")+1);
							String nick = aggComp.substring(aggComp.indexOf(":")+1,aggComp.lastIndexOf(":"));
							//boolean isAnchorNick = anchorCompNick != null && anchorCompNick.equals(nick);

							String startBold = "";
							String endBold = "";
							String anchorComponentStr = "no";
							if(anchorCompNick != null && anchorCompNick.equals(nick))
							{
								anchorComponentStr = "yes";
								startBold = "<b>";
								endBold = "</b>";
							}
							countColumn++;
							String autoAssociateStr="";
							if(isElementZone)
							{
								autoAssociateStr="&autoAssociatedToZone="+autoAssociatedToZone;
							}
							if(countColumn == 3)
							{
								tmpStr = tmpStr + "<td nowrap style='padding-top:3px;padding-bottom:5px;width:33%;padding-left:8px';><a data-qtip='Anchor Component' data-qclass='yellowTip' href=\"/final/admin/aggNewServer.jsp?server="+EgURLEncoder.encode(nickPort,"UTF-8")+"&serverType="+EgURLEncoder.encode(aggCompType,"UTF-8")+"&modifyserver=true&elementType="+elementType+"&elementName="+name+"&operation=modify&serverGategory="+category+"&anchorComponent="+anchorComponentStr+autoAssociateStr+"&reqfrom=agg_show_types"+"\" id='mouse' style='font-weight:normal;text-decoration:none;vertical-align:top'>&nbsp;"+startBold+nick+endBold+"</a></td>";
								countColumn = 0;
								tmpStr = tmpStr + "</tr><tr>";
							}
							else
							{
								tmpStr = tmpStr + "<td nowrap style='padding-top:3px;padding-bottom:5px;width:33%;padding-left:8px'><a data-qtip='Anchor Component' data-qclass='yellowTip' href=\"/final/admin/aggNewServer.jsp?server="+EgURLEncoder.encode(nickPort,"UTF-8")+"&serverType="+EgURLEncoder.encode(aggCompType,"UTF-8")+"&modifyserver=true&elementType="+elementType+"&elementName="+name+"&operation=modify&serverGategory="+category+"&anchorComponent="+anchorComponentStr+autoAssociateStr+"&reqfrom=agg_show_types"+"\" id='mouse' style='font-weight:normal;text-decoration:none;vertical-align:top'>&nbsp;"+startBold+nick+endBold+"</a></td>";
							}
						}
						if(countColumn == 2)
						{
							tmpStr = tmpStr + "<td style='padding-top:3px;padding-bottom:5px;width:33%' align='left'>&nbsp;</td>";
						}
						if(countColumn == 1)
						{
							tmpStr = tmpStr + "<td style='padding-top:3px;padding-bottom:5px;width:33%' align='left'>&nbsp;</td><td style='padding-top:3px;padding-bottom:5px;width:33%' align='left'>&nbsp;</td>";
						}
					}
					tmpStr = tmpStr + "</tr></table></div>";
					gridRowValues.put("nickname",tmpStr);

					String mofifyComponentHref="/final/admin/aggDispServer.jsp?comptype="+aggCompType+"&elementType="+elementType+"&elementName="+name+"&category="+category+"&reqfrom=agg_show_types";//+"&operation=displayComponents";

					String addComponentHref="/final/admin/aggNewServer.jsp?server=new&serverType="+aggCompType+"&elementType="+elementType+"&elementName="+name+"&operation=add&serverGategory="+category+"&reqfrom=agg_show_types";

					String manageUnmanageHref="/final/admin/aggConfigEnv.jsp?srvtype="+aggCompType+"&server="+aggCompType+"&s_component="+aggCompType+"&backButNeed=yes&category="+category;

					gridRowValues.put("action",(mofifyComponentHref+"@"+addComponentHref+"@"+manageUnmanageHref));
					gridRowValues.put("isShow","true"+"&m"+componentCount);
				}
				else
				{
					String tmpStr = "<div style='margin-left:50px'><table class='mylink' cellspacing=\"0\" cellpadding=\"4\" border=\"0\" width=\"90%\" align=\"left\"><tr>";
					tmpStr = tmpStr + "<td style='padding-top:3px;padding-bottom:5px;width:33%;padding-left:10px' class='comp_not_found'>&nbsp;<i>No components created</i></td>";
					tmpStr = tmpStr + "<td style='padding-top:3px;padding-bottom:5px;width:33%' align='left'>&nbsp;</td><td style='padding-top:3px;padding-bottom:5px;width:33%' align='left'>&nbsp;</td></tr></table></div>";
					gridRowValues.put("nickname",tmpStr);

					//gridRowValues.put("nickname","<span style='margin-left:20px;padding-top:3px;padding-bottom:5px;'>No components created</span>");
					//gridRowValues.put("nickname","No components created");


					String mofifyComponentHref="";
					String addComponentHref="/final/admin/aggNewServer.jsp?server=new&serverType="+aggCompType+"&elementType="+elementType+"&elementName="+name+"&operation=add&serverGategory="+category+"&reqfrom=agg_show_types";
					String manageUnmanageHref="";
					gridRowValues.put("action",(mofifyComponentHref+"@"+addComponentHref+"@"+manageUnmanageHref));
					gridRowValues.put("isShow","false"+"&m"+componentCount);
				}
				gridValuesArray.add(gridRowValues);
			}
			rootJson.put("gridValues",gridValuesArray);
		}
	}
	rootJson.put("success","true");
	out.println(rootJson.toString());
%>
<%
}
catch(Exception e)
{
	e.printStackTrace();
}
%>