<%
/*
 *	Name            :   UserLicenseCountDetailsJson.jsp
 *	Purpose         :   To provide details about user License counts. 
 */
%>

<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import = "com.eg.EgCertUsage"%>

<%@ page import = "java.sql.*"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="net.sf.json.JSONArray"%>
<%@ page import="com.egurkha.util.StringUtils"%>

<%
	EgCertUsage certUsage = new EgCertUsage();
	JSONObject rootJSON = new JSONObject();
	String userName = request.getParameter("userName");
	JSONArray jsonArr = new JSONArray();
	String orgUnitName=request.getParameter("orgUnitName");
	IniFile userCompMapIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini");
	String[] userNameVars = userCompMapIni.getVariables("Users_Allowed_Count");
	ArrayList availUsersList = new ArrayList(Arrays.asList(userNameVars));
	ArrayList userAllowedLimits = new ArrayList();
    List userServers = new ArrayList();

	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	if(isLimitedAdmin)
	{
		User user = registry.getUser(session.getId());
		userServers = user.getServers(false);
	}

	String userLanguage = _user.getLanguage();
	EgMappingInfo mappingInfo = new EgMappingInfo(userLanguage);
	EgExternalInfo extInfo = new EgExternalInfo("manager");
	EgDiscInfo discInfo = new EgDiscInfo("manager");
	EgUuidInfo uuidInfo = new EgUuidInfo();
	egurkha.UserBean userBean = new egurkha.UserBean();
	String totalMon_Org ="";
	String basicMon_Org = "-1";
	String networkDev_Org = "";
	int allowedTotalCnt=0,allowedBasicCnt=0,allowedPremuCnt=0;
	String monType = request.getParameter("monType");
	ArrayList details = new ArrayList();
	int detailsCount = 0;
	ArrayList TotalMonitorDetail = new ArrayList();
	ArrayList BasicMonitorDetail = new ArrayList();
	ArrayList PremMonitorDetail = new ArrayList();
	ArrayList NetworkMonitorDetail = new ArrayList();
	ArrayList MonitorUserDetail = new ArrayList();
	//For CSV
	List csvData = new ArrayList();
	String csvRow = "";
	ArrayList basicToPrem = new ArrayList();
	//For manager -EGENTERPRISE
	if (userName != null && userName.equalsIgnoreCase("egenterprise")) 
	{
		//certUsage.setUserName(userName);
		if(monType.equalsIgnoreCase("Total Monitors"))
		{
			ArrayList basAgents = userBean.getCurrentBasicAgents();
			ArrayList alBasAgents = userBean.getAgentlessBasic();
			ArrayList preAgents = userBean.getPremiumAgents();
			ArrayList alPreAgents = userBean.getAgentlessPremium();
			details.addAll(basAgents);
			details.addAll(alBasAgents);
			details.addAll(preAgents);
			details.addAll(alPreAgents);
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,"TotalMonitors",userServers);
		}
		else if(monType.equalsIgnoreCase("Basic Monitors"))
		{
			ArrayList basAgents = userBean.getCurrentBasicAgents();
			ArrayList alBasAgents = userBean.getAgentlessBasic();
			details.addAll(basAgents);
			details.addAll(alBasAgents);
			//If basic comps exceeds the allowed count then it will consume premium license if exist.
			int allowedBasic = EgMemInfo.basicAgents;
			if (allowedBasic > 0)
			{
				int usedBasic = details.size();
				if (usedBasic > allowedBasic)
				{
					Collections.sort(details);
					details = new ArrayList(details.subList(0,allowedBasic));
				}
			}
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,"BasicMonitors",userServers);
		}
		else if(monType.equalsIgnoreCase("Premium Monitors"))
		{
			ArrayList preAgents = userBean.getPremiumAgents();
			ArrayList alPreAgents = userBean.getAgentlessPremium();
			details.addAll(preAgents);
			details.addAll(alPreAgents);
			//If basic comps exceeds the allowed count then it will consume premium license if exist.
			int allowedBasic = EgMemInfo.basicAgents;
			if (allowedBasic > 0)
			{
				ArrayList tmpDetails = new ArrayList(userBean.getCurrentBasicAgents());
				tmpDetails.addAll(userBean.getAgentlessBasic());		
				int usedBasic = tmpDetails.size();
				if (usedBasic > allowedBasic)
				{
					Collections.sort(tmpDetails);
					List tmpPremuAgents = tmpDetails.subList(allowedBasic,tmpDetails.size());
					details.addAll(tmpPremuAgents);
				}
			}
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,"PremiumMonitors",userServers);
		}
		else if(monType.equalsIgnoreCase("Network device"))
		{
			details = discInfo.getAllNetworkDevices();
			if (details == null) details=new ArrayList();
			details = new ArrayList(details);
			details = getRefinedList(details,mappingInfo);
		}
		else if(monType.equalsIgnoreCase("Monitor users"))
		{
			EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
			String connStatus = egDb.setConnection();
			if (connStatus.equals("CONNECTED"))
			{
				try
				{
					ResultSet rs = egDb.SelectExec("SELECT user_id FROM user_info");
					while(rs.next())
					{
						String uname=rs.getString("user_id");
						boolean isDefUser = User.isDefaultUser(uname);
						if (!isDefUser)
						{
							details.add(uname);
						}
					}
					rs.close();
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					try
					{
						egDb.releaseConnection(false);
					}
					catch(Exception e)
					{
						egDb.releaseConnection(true);
					}
				}
			}
			EgDbAdapterTypeUI.releaseObject(egDb);
		}
	//	details = getTypesForNick(details,discInfo,extInfo,mappingInfo);
		detailsCount = details.size();
	}
	//For All users Excpet ManAger
	if (userName != null && !(userName.equalsIgnoreCase("egenterprise")))
	{
		if (availUsersList.contains(userName))
		{
			String value = userCompMapIni.getValue("Users_Allowed_Count",userName);
			value = EgCrypt.decrypt(value);
			userAllowedLimits = StringUtils.egTokenizer(value,"#");
		}
		if (userAllowedLimits != null && userAllowedLimits.size() > 0)
		{
			totalMon_Org = userAllowedLimits.get(0).toString();
			basicMon_Org = userAllowedLimits.get(1).toString();
			allowedTotalCnt = Integer.parseInt(totalMon_Org);
			allowedBasicCnt = Integer.parseInt(basicMon_Org);
			allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
		}
		certUsage.setUserName(userName);
		TotalMonitorDetail = certUsage.getTotalMonitorsForUser();
		BasicMonitorDetail = certUsage.getBasicMonitorsForUser();
		PremMonitorDetail = certUsage.getPremiumMonitorsForUser();
		int BasicMonitorDetailSize = BasicMonitorDetail.size();
		MonitorUserDetail = uuidInfo.getAllSubOrgsAndUsers(userName);
		//To consume Premium license if no Basic License or Basic License Limit exceeds  
		if (!basicMon_Org.equals("-1"))
		{
			int allowedBas = Integer.parseInt(basicMon_Org);
			if (BasicMonitorDetailSize > allowedBas)
			{
				int rmCount = BasicMonitorDetailSize - allowedBas;
				//System.out.println("rmCount"+rmCount);
				//System.out.println("BasicMonitorDetailSize"+BasicMonitorDetailSize);
				//System.out.println("allowedBas"+allowedBas);

				for(int i=0; i<rmCount; i++)
				{
					basicToPrem.add(BasicMonitorDetail.get(i));
				}
			}
			for(int i=0;i<basicToPrem.size();i++)
			{
				BasicMonitorDetail.remove(basicToPrem.get(i));
			}
		}
		
		ArrayList tmpuserServers = new ArrayList();
		if(userServers.size() == 0) //to get the servers of corresponding user choosen. -- Bug Id: 19091
		{	
			ErUserData usrObj = new ErUserData(userName,false);
			Vector usrServers =  usrObj.getServersWithType();
			Iterator it = usrServers.iterator();
			while(it.hasNext())
			{
				String compo =(String) it.next();
				int lastInd = compo.lastIndexOf(":");
				String cmpType = compo.substring(lastInd+1);
				String nickandPort = compo.substring(0,lastInd-1);
				tmpuserServers.add(cmpType+":"+nickandPort);
			}
		}
		if(tmpuserServers!=null && tmpuserServers.size() > 0)
		{
			userServers.addAll(tmpuserServers);
		}

		if(monType.equalsIgnoreCase("Total Monitors"))
		{
			details.addAll(TotalMonitorDetail);
			detailsCount = TotalMonitorDetail.size();
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,userServers);
		}
		else if(monType.equalsIgnoreCase("Basic Monitors"))
		{
			detailsCount = BasicMonitorDetail.size();
			details.addAll(BasicMonitorDetail);
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,userServers);
		}
		else if(monType.equalsIgnoreCase("Premium Monitors"))
		{
			details.addAll(PremMonitorDetail);
			detailsCount = PremMonitorDetail.size();
			int basicToPremSize=basicToPrem.size(); 
			if(basicToPremSize !=0 )
			{
				details.addAll(basicToPrem);
				detailsCount = PremMonitorDetail.size()+basicToPremSize;
			}
			details = getTypesForNick(details,discInfo,extInfo,mappingInfo,userServers);
		}
		else if(monType.equalsIgnoreCase("Network device"))
		{
			NetworkMonitorDetail = certUsage.getNetworkDevicesForUser();
			String compName = "";
			int compNameSize = NetworkMonitorDetail.size();
			for(int l =0 ; l< compNameSize ; l++)
			{
				String app = (String)NetworkMonitorDetail.get(l);
				int idx = app.indexOf(":");
				String appType = app.substring(0,idx);
				app = app.substring(app.indexOf(":")+1);
				app = app.replace(":NULL","");
				compName += app+"("+appType+")";
				compName = compName + ",";
			}
			if(compName.endsWith(","))
			{
				compName = compName.substring(0,compName.length()-1);
			}
			if (details == null)
				{ 
				details=new ArrayList();
				}
			ArrayList compList =  new ArrayList(Arrays.asList(compName.split(",")));
			details.addAll(compList);
			detailsCount = NetworkMonitorDetail.size();
		}
		//details = getTypesForNick(details,discInfo,extInfo,mappingInfo);
		//monitoruser no need to getnick name
		if(monType.equalsIgnoreCase("Monitor users"))
		{
			if (MonitorUserDetail != null && MonitorUserDetail.size() > 0)
			{
				MonitorUserDetail.remove(userName);
			}
			details.addAll(MonitorUserDetail);
			detailsCount = MonitorUserDetail.size();
		}
	}
		csvData.add("Used count Report");
		csvData.add("");
		csvData.add(orgUnitName+" ");
		csvData.add("User : "+userName);
		csvData.add(monType+"("+details.size()+")");
		String compo="";
		csvData.add("");
		for(int i=0;i<details.size();i++)
		{
			csvData.add(details.get(i));
		}
		if(detailsCount%3 == 1)
		{
			details.add("");
			details.add("");
		}
		else if (detailsCount%3 == 2)
		{
			details.add("");
		}
		for(int c=0; c<detailsCount; c+=3)
		{
			JSONObject tmpObj = new JSONObject();
			tmpObj.put("col_1",details.get(c).toString());
			tmpObj.put("col_2",details.get(c+1).toString());
			tmpObj.put("col_3",details.get(c+2).toString());
			jsonArr.add(tmpObj);
		}
	session.setAttribute("list",csvData);
	session.setAttribute("isAuditlogCSV","true");
	rootJSON.put("details",jsonArr);
	rootJSON.put("Count",detailsCount);
	out.println(rootJSON);
%>

<%!
	public ArrayList getRefinedList(ArrayList src,EgMappingInfo mappingInfo)
	{
		int srcCount = src.size();
		ArrayList result = new ArrayList();
		for (int i=0; i < srcCount; i++)
		{
			String comp = (String)src.get(i);
			if (comp.toLowerCase().endsWith(":null"))
				comp = comp.substring(0,comp.lastIndexOf(":"));
			int idx = comp.indexOf(":");
			if (idx > -1)
			{
				String type = comp.substring(0,idx);
				comp = comp.substring(idx+1) +" ("+mappingInfo.getComponentTypeDescription(type)+")";
			}

			result.add(comp);
		}
		return result;
	}

	public ArrayList getTypesForNick(ArrayList details, EgDiscInfo discInfo, EgExternalInfo extInfo, EgMappingInfo mappingInfo,List  userServers)
	{
		return getTypesForNick(details, discInfo, extInfo, mappingInfo,"",userServers);
	}

	public ArrayList getTypesForNick(ArrayList details, EgDiscInfo discInfo, EgExternalInfo extInfo, EgMappingInfo mappingInfo,String monitorType,List userServers)
	{
		List tempDetails = new ArrayList();
		ArrayList basicTypes = EgInstallInfo.getBasicTypes();
		EgUsersInfo usersInfo = new EgUsersInfo();
		boolean userCert = usersInfo.isUserBasedLicense();
		ArrayList userTypes = usersInfo.getAllUserBasedCompTypes();
		ArrayList extAgents = new ArrayList();
		String[] exts = extInfo.getAllExternalAgents();
		if (exts != null)
		{
			extAgents = new ArrayList(Arrays.asList(exts));
		}
		for (int d=0; d<details.size(); d++)
		{
			String nick = (String)details.get(d);
			List compTypes = discInfo.getServerTypesForNick(nick);
			if (monitorType.equals("BasicMonitors"))
			{
				compTypes.retainAll(basicTypes);
			}
			else if (userCert && (monitorType.equals("PremiumMonitors") || monitorType.equals("TotalMonitors")))
			{
				compTypes.removeAll(userTypes);
			}

			ArrayList tempcompTypes = new ArrayList();
			if(userServers.size() > 0) //for limited user :  BUGID -19091
			{
				Iterator it = userServers.iterator();
				while(it.hasNext())
				{
					String userSrver = it.next().toString();
					if(userSrver.indexOf(":"+nick+":") > 0)
					{
						String compType = userSrver.substring(0,userSrver.indexOf(":")); 
						tempcompTypes.add(compType);
					}
				}
			}

			if(tempcompTypes!=null && tempcompTypes.size() > 0 )
			{
				compTypes.retainAll(tempcompTypes);
			}

			String type = "";
			if (compTypes != null && compTypes.size() > 0)
			{
				for (int c=0; c < compTypes.size(); c++)
				{
					type = compTypes.get(c).toString();
					if (!basicTypes.contains(type))
					{
						type = mappingInfo.getComponentTypeDescription(type);
						break;
					}
					type = "";
				}
				if (type.equals(""))// Basic agents or basic consumes premium license
				{
					type = compTypes.get(0).toString();
					type = mappingInfo.getComponentTypeDescription(type);
				}
				if (extAgents.contains(nick))
				{
					type = "External Agent, "+type;
				}
			}
			else
			{
				type = "External Agent";
			}
			tempDetails.add(nick+" ("+type+")");
		}
		if (tempDetails.size() > 0)
		{
			details = new ArrayList(tempDetails);
		}
		return details;
	}
%>



