<%
/**
 *	File name		:	ZoneAndUserWiseReportJson.jsp
 *	Purpose			:	This page provides details about Zone and eGUser wise usage
 */
%>
<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="com.egurkha.util.StringUtils"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="net.sf.json.JSONArray"%>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "java.util.Calendar"%>
<%@ page import = "java.util.Date"%>
<%@ page import = "java.text.SimpleDateFormat"%>
<%@ page import = "java.text.DateFormat"%>

<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json;charset=UTF-8");
	
	JSONObject jsonBaseObj = new JSONObject();
	ArrayList elementsList = new ArrayList();

	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	boolean isMspModel = EgUuidInfo.isMspModel();

	String tab = request.getParameter("tab");
	String srcStr = request.getParameter("searchStr");
	srcStr = egurkha.EgUIUtils.decodeSecurityChar(srcStr);
	String zoneAttr = request.getParameter("zoneAttr");
	EgExternalInfo extInfo = new EgExternalInfo("manager");
	EgDiscInfo discInfo = new EgDiscInfo("manager");
	EgUsersInfo usersInfo = new EgUsersInfo();
	String userLanguage = _user.getLanguage();
	IniUI iniUI = IniUI.getInstance();
	if (userLanguage == null)
		userLanguage = iniUI.getDefaultLanguage();
	EgMappingInfo mappingInfo = new EgMappingInfo(userLanguage);
	
	EgCertUsage certUsage = new EgCertUsage();
	EgGroupInfo grInf = new EgGroupInfo();
	ArrayList nameList = new ArrayList();
	boolean isUserBased = false;
	if (tab != null && tab.equals("User"))
	{
		isUserBased = true;
	}

	JSONObject jsonObj = new JSONObject();
	boolean isCCUserCertEnabled = EgInstallInfo.isconcurrentUserLicense;
	boolean isNamedUserEnabled = EgInstallInfo.isnamedUserLicense;
	boolean isUserCertMgr = usersInfo.isUserBasedLicense();
	IniFile servicesIni = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_services.ini");
	String vdiUsrsSplitUp = servicesIni.getValue("ZoneAndUserCertUsage","VDIUsersSplitup");
	boolean showVDIUsersSplitUp = false;
	if (vdiUsrsSplitUp != null && (vdiUsrsSplitUp.equalsIgnoreCase("yes") || vdiUsrsSplitUp.equalsIgnoreCase("true")))
	{
		showVDIUsersSplitUp = true;
	}
	String infiniteCols = servicesIni.getValue("ZoneAndUserCertUsage","InfiniteAllowedCountColumns");
	boolean showInfiniteAllowedCols = false;
	if (infiniteCols != null && (infiniteCols.equalsIgnoreCase("yes") || infiniteCols.equalsIgnoreCase("true")))
	{
		showInfiniteAllowedCols = true;
	}

	//for CSV Report Date
	String userDateFormat = _user.getUserDateFormat();
	String userDateTimeFormat = userDateFormat+" HH:mm:ss";
	Date currDate = new Date();
	SimpleDateFormat smdf = new SimpleDateFormat(userDateTimeFormat);
	String currDateStr = smdf.format(currDate); 

	//For CSV
	List csvData = new ArrayList();
	String csvRow = "";
	String repTitle = "License usage report by zones";
	String repDate = "Report generated on"+","+currDateStr+"";
	String colHeads =  "Zones";
	String colSubHd = "";
	if (isUserBased)
	{
		repTitle = "License usage report by users";
		colHeads =  "Users";
	}
	colHeads += ",Total Monitors,,Basic Monitors,,Premium Monitors,,";
	colSubHd += ",Used,Usage (%),Used,Usage (%),Used,Usage (%),";
	if (!isLimitedAdmin)
	{
		colHeads += "External Agents,,";
		colSubHd += "Used,Usage (%),";
	}
	
	if (isUserCertMgr)
	{
		if (EgInstallInfo.isnamedUserLicense)
		{
			colHeads += "Named Users,,";
		}
		else
		{
			colHeads += "Concurrent Users,,";
		}
		if (showVDIUsersSplitUp)
		{
			colSubHd += "Used(Citrix / VDI / Terminal),Peak usage last month,Peak usage date,Usage (%),";
		}
		else
		{
			colSubHd += "Used,Peak usage last month,Peak usage date,Usage (%),";
		}
	}

	// CSV - Headings
	if(isLimitedAdmin)
	{
		if(EgMemInfo.networkDevices != -1 || showInfiniteAllowedCols)
		{
			colHeads += "NetworkDevices,,";
			colSubHd += "Used,Usage (%),";
		}
	}
	else
	{
		if (EgMemInfo.targets != -1 || showInfiniteAllowedCols)
		{
			colHeads += "Monitored Targets,,";
			colSubHd += "Used,Usage (%),";
		}
		if(EgMemInfo.applications != -1 || showInfiniteAllowedCols)
		{
			colHeads += "Applications,,";
			colSubHd += "Used,Usage (%),";
		}
		if(EgMemInfo.networkDevices != -1 || showInfiniteAllowedCols)
		{
			colHeads += "NetworkDevices,,";
			colSubHd += "Used,Usage (%),";
		}
		if(EgMemInfo.sites != -1 || showInfiniteAllowedCols)
		{
			colHeads += "Services,,";
			colSubHd += "Used,Usage (%),";
		}
		if(EgMemInfo.segments != -1 || showInfiniteAllowedCols)
		{
			colHeads += "Segments";
			colSubHd += "Used,Usage (%)";
		}
	}

//	colHeads += "Monitored Targets,,Applications,,NetworkDevices,,Services,,Segments";
//	colSubHd += "Used,Usage (%),Used,Usage (%),Used,Usage (%),Used,Usage (%),Used,Usage (%)";
	csvData.add(repTitle);
	csvData.add(repDate);
	csvData.add("");
	csvData.add(colHeads);
	csvData.add(colSubHd);
	if (isUserBased)
	{
		EgUuidInfo uuidInfo = new EgUuidInfo();
		ArrayList eGUsers = certUsage.getAllLimitedCompAccessUsers();
		String userId = _user.getLoginID();
		String user_id = (uuidInfo.isUser(userId) && uuidInfo.hasOURole(userId)) ? uuidInfo.getDirectDependentOU(userId) : userId;
		if (srcStr != null && srcStr.trim().length() > 0)
		{
			ArrayList srcTokens = StringUtils.egTokenizer (srcStr, " ", false, false, true);
			for (int e=0; e<eGUsers.size(); e++)
			{
				String egUser = (String)eGUsers.get(e);
				for (int s=0; s < srcTokens.size(); s++)
				{
					String srcToken = srcTokens.get(s).toString().toLowerCase();
					if (egUser.toLowerCase().indexOf(srcToken) != -1)
					{
						nameList.add(egUser);
					}
				}
			}
		}
		else if(eGUsers != null)
		{
			nameList.addAll(eGUsers);
		}
		if (!userId.equalsIgnoreCase("admin"))
		{
			TreeSet specificUsers = uuidInfo.getAllUsersUnderOrg(user_id);
			nameList.retainAll(specificUsers);
		}
	}
	else // Zones
	{
		String[] zonesArr = grInf.getZoneNames();
		ArrayList eGZones = new ArrayList();
		if (zonesArr != null)
		{
			eGZones = new ArrayList(Arrays.asList(zonesArr));
		}
		if (srcStr != null && srcStr.trim().length() > 0)
		{
			ArrayList srcTokens = StringUtils.egTokenizer (srcStr, " ", false, false, true);
			for (int e=0; e<eGZones.size(); e++)
			{
				String eGZone = (String)eGZones.get(e);
				for (int s=0; s < srcTokens.size(); s++)
				{
					String srcToken = srcTokens.get(s).toString().toLowerCase();
					if (eGZone.toLowerCase().indexOf(srcToken) != -1)
					{
						nameList.add(eGZone);
					}
				}
			}
		}
		else
		{
			nameList.addAll(eGZones);
		}
	}
	int nameListSize = nameList.size();
	if (nameListSize > 0)
	{
		jsonBaseObj.put("enableSearch",true);
	}
	else
	{
		jsonBaseObj.put("enableSearch",false);
	}
	//Named or CC users
	HashMap userCertInfo = new HashMap();

	if(isUserCertMgr)
	{
		if (isUserBased)
		{
			userCertInfo = certUsage.getCertUsersDetailsForUsers();
		}
		else
		{
			userCertInfo = certUsage.getCertUsersDetailsForZones();
		}
	}

	JSONArray gridArr = new JSONArray();
	if(nameListSize == 0)
	{
		jsonBaseObj.put("hideExtAgtCol",true);
		jsonBaseObj.put("hideMonTrgtsCol",true);
		jsonBaseObj.put("hideAppsCol",true);
		jsonBaseObj.put("hideServsCol",true);
		jsonBaseObj.put("hideSegsCol",true);
		if (!isUserCertMgr)
		{
			jsonBaseObj.put("hideUserCertCol",true);
		}
		gridArr.add(jsonObj);
		jsonBaseObj.put("gridDetails",gridArr);
	}
	Collections.sort(nameList,String.CASE_INSENSITIVE_ORDER);
	IniFile userCompMapIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini");
	String[] userNameVars = userCompMapIni.getVariables("Users_Allowed_Count");
	EgUuidInfo uuidInfo = new EgUuidInfo();
	ArrayList availUsersList = new ArrayList(Arrays.asList(userNameVars));

	for (int u=0; u < nameListSize; u++)
	{
		String name = (String)nameList.get(u);
		ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,name);
		int totalAllowedCount = 0;
		int basicAllowedCount = 0;
		int premiumAllowedCount = 0;
		if(userAllowedLimits!=null && userAllowedLimits.size() > 0 )
		{
			 totalAllowedCount = Integer.parseInt(userAllowedLimits.get(0).toString());
			 basicAllowedCount = Integer.parseInt(userAllowedLimits.get(1).toString());
			 premiumAllowedCount = totalAllowedCount - basicAllowedCount;
		}	
		if (isUserBased) 
		{
			certUsage.setUserName(name);
		}
		else 
		{
			certUsage.setZoneName(name);
			totalAllowedCount = EgMemInfo.agents;
			basicAllowedCount= EgMemInfo.basicAgents;
			premiumAllowedCount = totalAllowedCount;
			if(totalAllowedCount != -1 && basicAllowedCount != -1)
			{
				premiumAllowedCount = totalAllowedCount - basicAllowedCount;
			}
		}
		jsonObj = new JSONObject();
		jsonObj.put("Name",name);
		csvRow = name;
		HashMap detailsMap = new HashMap();
		// Total monitors
		if (isUserBased)
		{
			detailsMap = certUsage.getTotalMonitorsDetailsForUser(totalAllowedCount);
		}
		else
		{
			detailsMap = certUsage.getTotalMonitorsDetailsForZone(totalAllowedCount);
		}
		String used = (String)detailsMap.get("Used");
		String usag = (String)detailsMap.get("Usage");
		if (used.equalsIgnoreCase("0"))
		{
			usag = "0";
		}
		jsonObj.put("TotalCnt",used);
		jsonObj.put("TotalUsg",usag);
		csvRow += ","+used+","+usag;
		//Basic monitors
		if (isUserBased)
		{
			detailsMap = certUsage.getBasicMonitorsDetailsForUser(basicAllowedCount);
		}
		else
		{
			detailsMap = certUsage.getBasicMonitorsDetailsForZone(basicAllowedCount);
		}
		used = (String)detailsMap.get("Used"); 
		usag = (String)detailsMap.get("Usage");
		if (used.equalsIgnoreCase("0"))
		{
			usag = "0";
		}
		jsonObj.put("BasicCnt",used);
		jsonObj.put("BasicUsg",usag);
		csvRow += ","+used+","+usag;
		//Premium monitors
		if (isUserBased)
		{
			detailsMap = certUsage.getPremiumMonitorsDetailsForUser(premiumAllowedCount);
		}
		else
		{
			detailsMap = certUsage.getPremiumMonitorsDetailsForZone(premiumAllowedCount);
		}
		used = (String)detailsMap.get("Used"); 
		usag = (String)detailsMap.get("Usage");
		if (used.equalsIgnoreCase("0"))
		{
			usag = "0";
		}
		jsonObj.put("PremiumCnt",used);
		jsonObj.put("PremiumUsg",usag);
		csvRow += ","+used+","+usag;
		//External agents
		if (isLimitedAdmin)
		{
			jsonBaseObj.put("hideExtAgtCol",true);
		}
		else
		{
			if (isUserBased)
			{
				detailsMap = certUsage.getExternalAgentsDetailsForUser();
			}
			else
			{
				detailsMap = certUsage.getExternalAgentsDetailsForZone();
			}
			used = (String)detailsMap.get("Used"); 
			usag = (String)detailsMap.get("Usage");
			if (used.equalsIgnoreCase("0"))
			{
				usag = "0";
			}
			jsonObj.put("ExtAgentCnt",used);
			jsonObj.put("ExtAgentUsg",usag);
			csvRow += ","+used+","+usag;
		}
		//UsersCert
		if (isUserCertMgr)
		{	
			String total = "0";
			String ctxUsrs = "-";
			String vdiUsrs = "-";
			String trmUsrs = "-";
			String peakCnt = "-";
			String peakDate = "-";
			IniFile uiIni = new IniFile(EgConfigInfo.egMgrConfigDir+"eg_ui.ini");
			String currDateFormat = uiIni.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
			if (currDateFormat == null || currDateFormat.trim().length() == 0)
			{
				currDateFormat = "MMM dd, yyyy";
			}
			HashMap userMap = (HashMap)userCertInfo.get(name);
			if (userMap != null)
			{
				Iterator it = userMap.keySet().iterator();
				while (it.hasNext())
				{
					String type = (String)it.next();
					String cnt = (String)userMap.get(type);
					int idx = cnt.indexOf(".");
					if (idx != -1)
						cnt = cnt.substring(0,idx);
					if (type.equalsIgnoreCase("Total"))
					{
						total = cnt;
					}
					else if (type.equalsIgnoreCase("Citrix Users"))
					{
						ctxUsrs = cnt;
					}
					else if (type.equalsIgnoreCase("VDI Users"))
					{
						vdiUsrs = cnt;
					}
					else if (type.equalsIgnoreCase("Terminal Users"))
					{
						trmUsrs = cnt;
					}
					else if (type.equalsIgnoreCase("peakCount"))
					{
						peakCnt = cnt;
					}
					else if (type.equalsIgnoreCase("peakDate"))
					{
						peakDate = cnt;
					}
				}
			}
			long allowedCnt = usersInfo.getUserAllowedCount();

			String totPercent = certUsage.getUsedInPercentage(allowedCnt+"",total,"");
			if (showVDIUsersSplitUp  && !total.equals("0"))
			{
				total += " ("+ctxUsrs+" / "+vdiUsrs+" / "+trmUsrs+")";
			}
			int dotIdx = peakCnt.indexOf(".");
			if (dotIdx > -1)
			{
				peakCnt = peakCnt.substring(0,dotIdx);
			}
			if (peakDate!=null && !peakDate.trim().equals("-"))
			{
				peakDate = com.egurkha.util.DateUtil.changeDateFormat(peakDate,"yyyy-MM-dd HH:mm:ss",currDateFormat);				
			}
			jsonObj.put("UserCnt",total);
			jsonObj.put("UserUsg",totPercent);
			jsonObj.put("peakUsg",peakCnt);
			jsonObj.put("peakDate",peakDate);
			peakDate = "\""+peakDate+"\"";
			csvRow += ","+total+","+peakCnt+","+peakDate+","+totPercent;
		}
		else
		{
			jsonBaseObj.put("hideUserCertCol",true);
		}

		if (isLimitedAdmin)
		{
			//NW devices
			if(EgMemInfo.networkDevices != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getNetworkDevicesDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getNetworkDevicesDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("NWDevicesCnt",used);
				jsonObj.put("NWDevicesUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideNwDevsCol",true);
			}
			jsonBaseObj.put("hideMonTrgtsCol",true);
			jsonBaseObj.put("hideAppsCol",true);
			jsonBaseObj.put("hideServsCol",true);
			jsonBaseObj.put("hideSegsCol",true);
			csvData.add(csvRow);
		}
		else
		{
			//Monitored Targets
			if (EgMemInfo.targets != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getMonitoredTargetsDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getMonitoredTargetsDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");	
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("MonTrgtCnt",used);
				jsonObj.put("MonTrgtUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideMonTrgtsCol",true);
			}
		
			//Apps
			if(EgMemInfo.applications != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getApplicationsDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getApplicationsDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("AppsCnt",used);
				jsonObj.put("AppsUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideAppsCol",true);
			}

			//NW devices
			if(EgMemInfo.networkDevices != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getNetworkDevicesDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getNetworkDevicesDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("NWDevicesCnt",used);
				jsonObj.put("NWDevicesUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideNwDevsCol",true);
			}
			
			//Services
			if(EgMemInfo.sites != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getServicesDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getServicesDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("ServicesCnt",used);
				jsonObj.put("ServicesUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideServsCol",true);
			}

			//Segments
			if( EgMemInfo.segments != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					detailsMap = certUsage.getSegmentsDetailsForUser();
				}
				else
				{
					detailsMap = certUsage.getSegmentsDetailsForZone();
				}
				used = (String)detailsMap.get("Used"); 
				usag = (String)detailsMap.get("Usage");
				if (used.equalsIgnoreCase("0"))
				{
					usag = "0";
				}
				jsonObj.put("SegmentsCnt",used);
				jsonObj.put("SegmentsUsg",usag);
				csvRow += ","+used+","+usag;
			}
			else
			{
				jsonBaseObj.put("hideSegsCol",true);
			}
			csvData.add(csvRow);
		}
		gridArr.add(jsonObj);
		jsonBaseObj.put("gridDetails",gridArr);
	}

	for (int j=0; j < nameListSize; j++)
	{
		JSONArray jsonArr = new JSONArray();
		ArrayList detailsArray = new ArrayList();
		String names = (String)nameList.get(j);
		if (isUserBased)
		{
			certUsage.setUserName(names);
		}
		else 
		{
			certUsage.setZoneName(names);
		}
		csvRow = "";
		csvData.add(csvRow);
		csvRow =  names;
		csvData.add(csvRow);

		//Total monitors
		if (isUserBased)
		{
			elementsList = certUsage.getTotalMonitorsForUser();
			detailsArray.addAll(elementsList);
		}
		else
		{
			elementsList = certUsage.getTotalMonitorsForZone();
			detailsArray.addAll(elementsList);
		}
		detailsArray = getTypesForNick(detailsArray,discInfo,extInfo,mappingInfo);
		String compName = "";
		int compNameSize = detailsArray.size();
		for(int l =0 ; l< compNameSize ; l++)
		{
			compName += (String)detailsArray.get(l) + ",";
		}
		if(compName.endsWith(","))
		{
			compName= compName.substring(0,compName.length()-1);
		}
		if(compName!="")
		{
			csvRow =  "Total Monitors" + "," + compName;
			csvData.add(csvRow);
		}

		//Basic monitors
		detailsArray = new ArrayList();
		if (isUserBased)
		{
			elementsList = certUsage.getBasicMonitorsForUser();
			detailsArray.addAll(elementsList);
		}
		else
		{
			elementsList = certUsage.getBasicMonitorsForZone();
			detailsArray.addAll(elementsList);
		}
		detailsArray = getTypesForNick(detailsArray,discInfo,extInfo,mappingInfo);
		compName = "";
		compNameSize = elementsList.size();
		for(int l =0 ; l< compNameSize ; l++)
		{
			compName += (String)detailsArray.get(l) + ",";
		}
		if(compName.endsWith(","))
		{
			compName= compName.substring(0,compName.length()-1);
		}
		if(compName!="")
		{
			csvRow = "Basic Monitors" + "," + compName;
			csvData.add(csvRow);
		}

		//Premium Components
		detailsArray = new ArrayList();
		if (isUserBased)
		{
			elementsList = certUsage.getPremiumMonitorsForUser();
			detailsArray.addAll(elementsList);
		}
		else
		{
			elementsList = certUsage.getPremiumMonitorsForZone();
			detailsArray.addAll(elementsList);
		}
		detailsArray = getTypesForNick(detailsArray,discInfo,extInfo,mappingInfo);
		compName = "";
		compNameSize = elementsList.size();
		for(int l =0 ; l< compNameSize ; l++)
		{
			compName += (String)detailsArray.get(l) + ",";
		}
		if(compName.endsWith(","))
		{
			compName= compName.substring(0,compName.length()-1);
		}
		if(compName!="")
		{
			csvRow = "Premium Monitors" + "," + compName;
			csvData.add(csvRow);
		}

		if(!isLimitedAdmin)
		{
			//External agents
			detailsArray = new ArrayList();
			if (isUserBased)
			{
				elementsList = certUsage.getExternalAgentsForUser();
				detailsArray.addAll(elementsList);
			}
			else
			{
				elementsList = certUsage.getExternalAgentsForZone();
				detailsArray.addAll(elementsList);
			}
			detailsArray = getTypesForNick(detailsArray,discInfo,extInfo,mappingInfo);
			compName = "";
			compNameSize = elementsList.size();

			for(int l =0 ; l< compNameSize ; l++)
			{
				compName += (String)detailsArray.get(l) + ",";
			}
			if(compName.endsWith(","))
			{
				compName= compName.substring(0,compName.length()-1);
			}
			if(compName!="")
			{
				csvRow = "External Agents" + "," + compName;
				csvData.add(csvRow);
			}
		}

		//Concurrent or Named Users 
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, -1);
		Date dateVal = cal.getTime();
		String dateValStr = dateVal.toString();
		dateValStr = dateValStr.substring(4,10)+","+dateValStr.substring(24,28);

		HashMap userMap =  new HashMap();
		HashMap userValMap = new HashMap();

		if(isCCUserCertEnabled || isNamedUserEnabled)
		{
			userValMap = usersInfo.getUserNamesForGroups(dateValStr,"Zone",names);
			if (userValMap != null)
			{
				Iterator it = userValMap.keySet().iterator();
				while (it.hasNext())
				{
					String type = (String)it.next();
					if(type.equalsIgnoreCase("Terminal Users"))
					{
						ArrayList userNamesArr = (ArrayList)userValMap.get(type);
						userMap.put("Terminal Users",userNamesArr);
						compName = "";
						compNameSize = userNamesArr.size();
						for(int l =0 ; l< compNameSize ; l++)
						{
							compName += (String)userNamesArr.get(l) + ",";
						}
						if(compName.endsWith(","))
						{
							compName= compName.substring(0,compName.length()-1);
						}
						if(compName!="")
						{
							csvRow = "Terminal Users" + "," + compName;
							csvData.add(csvRow);
						}
					}
					else if (type.equalsIgnoreCase("VDI Users"))
					{
						ArrayList userNamesArr = (ArrayList)userValMap.get(type);
						userMap.put("VDI Users",userNamesArr);
						compName = "";
						compNameSize = userNamesArr.size();
						for(int l =0 ; l< compNameSize ; l++)
						{
							compName += (String)userNamesArr.get(l) + ",";
						}
						if(compName.endsWith(","))
						{
							compName= compName.substring(0,compName.length()-1);
						}
						if(compName!="")
						{
							csvRow = "VDI Users" + "," + compName;
							csvData.add(csvRow);
						}
					}
					else if (type.equalsIgnoreCase("Citrix Users"))
					{
						ArrayList userNamesArr = (ArrayList)userValMap.get(type);
						userMap.put("Citrix Users",userNamesArr);
						compName = "";
						compNameSize = userNamesArr.size();
						for(int l =0 ; l< compNameSize ; l++)
						{
							compName += (String)userNamesArr.get(l) + ",";
						}
						if(compName.endsWith(","))
						{
							compName= compName.substring(0,compName.length()-1);
						}
						if(compName!="")
						{
							csvRow = "Citrix Users" + "," + compName;
							csvData.add(csvRow);
						}
					}
				}
			}
		}

		//Network Devices
		if(EgMemInfo.networkDevices != -1 || showInfiniteAllowedCols)
		{
			if (isUserBased)
			{
				elementsList = certUsage.getNetworkDevicesForZone();
			}
			else
			{
				elementsList = certUsage.getNetworkDevicesForZone();
			}
			compName = "";
			compNameSize = elementsList.size();
			for(int l =0 ; l< compNameSize ; l++)
			{
				String app = (String)elementsList.get(l);
				int idx = app.indexOf(":");
				String appType = app.substring(0,idx);
				app = app.substring(app.indexOf(":")+1);
				app = app.replace(":NULL","");
				compName += app+"("+mappingInfo.getComponentTypeDescription(appType)+")";
				compName = compName + ",";
			}
			if(compName.endsWith(","))
			{
				compName = compName.substring(0,compName.length()-1);
			}
			if(compName!="")
			{
				csvRow =  "NetworkDevices" + "," + compName;
				csvData.add(csvRow);
			}
		}
		
		if (!isLimitedAdmin)
		{
			//Monitored Targets
			if (EgMemInfo.targets != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					elementsList = certUsage.getMonitoredTargetsForUser();
				}
				else
				{
					elementsList = certUsage.getMonitoredTargetsForZone();
				}
				compName = "";
				compNameSize = elementsList.size();
				for(int l =0 ; l< compNameSize ; l++)
				{
					compName += (String)elementsList.get(l) + ",";
				}
				if(compName.endsWith(","))
				{
					compName= compName.substring(0,compName.length()-1);
				}
				if(compName!="")
				{
					csvRow = "Monitored Targets" + "," + compName;
					csvData.add(csvRow);
				}
			}

			//Applications 
			if(EgMemInfo.applications != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					elementsList = certUsage.getApplicationsForUser();
				}
				else
				{
					elementsList = certUsage.getApplicationsForZone();
				}
				compName = "";
				compNameSize = elementsList.size();
				for(int l =0 ; l< compNameSize ; l++)
				{
					String app = (String)elementsList.get(l);
					int idx = app.indexOf(":");
					String appType = app.substring(0,idx);
					app = app.substring(app.indexOf(":")+1);
					app = app.replace(":NULL","");
					compName += app+"("+mappingInfo.getComponentTypeDescription(appType)+")";
					compName = compName + ",";
				}
				if(compName.endsWith(","))
				{
					compName = compName.substring(0,compName.length()-1);
				}
				if(compName!="")
				{
					csvRow = "Applications" + "," + compName;
					csvData.add(csvRow);
				}
			}

			//Service Components
			if(EgMemInfo.sites != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					elementsList = certUsage.getServicesForUser();
				}
				else
				{
					elementsList = certUsage.getServicesForZone();
				}
				compName = "";
				compNameSize = elementsList.size();
				for(int l =0 ; l< compNameSize ; l++)
				{
					compName += (String)elementsList.get(l) + ",";
				}
				if(compName.endsWith(","))
				{
					compName= compName.substring(0,compName.length()-1);
				}
				if(compName!="")
				{
					csvRow = "Services" + "," + compName;
					csvData.add(csvRow);
				}
			}
			
			//Segments Component
			if(EgMemInfo.segments != -1 || showInfiniteAllowedCols)
			{
				if (isUserBased)
				{
					elementsList = certUsage.getSegmentsForUser();
				}
				else
				{
					elementsList = certUsage.getSegmentsForZone();
				}
				compName = "";
				compNameSize = elementsList.size();
				for(int l =0 ; l< compNameSize ; l++)
				{
					compName += (String)elementsList.get(l) + ",";
				}
				if(compName.endsWith(","))
				{
					compName= compName.substring(0,compName.length()-1);
				}
				if(compName!="")
				{
					csvRow =  "Segments" + "," + compName;
					csvData.add(csvRow);
				}
			}
		}
	}

	session.setAttribute("list",csvData);
	session.setAttribute("isAuditlogCSV","true");
	out.println(jsonBaseObj);

	
%>
<%!
	public ArrayList getTypesForNick(ArrayList details, EgDiscInfo discInfo, EgExternalInfo extInfo, EgMappingInfo mappingInfo)
	{
		List tempDetails = new ArrayList();
		ArrayList basicTypes = EgInstallInfo.getBasicTypes();
		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);
			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);
				}
			}
			else
			{
				type = "External Agent";
			}

			tempDetails.add(nick+" ("+type+")");
		}
		if (tempDetails.size() > 0)
		{
			details = new ArrayList(tempDetails);
		}
		return details;
	}

	public ArrayList getValidLicenseCount(ArrayList availUsersList, IniFile userCompMapIni, EgUuidInfo uuidInfo, String orgname)
	{
		ArrayList userAllowedLimits = new ArrayList();
		if (availUsersList.contains(orgname))
		{
			String value = userCompMapIni.getValue("Users_Allowed_Count",orgname);
			value = EgCrypt.decrypt(value);
			userAllowedLimits = StringUtils.egTokenizer(value,"#");
		}
		else
		{
			List orgNames = uuidInfo.getOrgNames(orgname,false);
			for (int i=0; i<orgNames.size(); i++)
			{
				String orgName = orgNames.get(i).toString().trim();
				String value = userCompMapIni.getValue("Users_Allowed_Count",orgName);
				if (value != null && value.length()>0)
				{
					value = EgCrypt.decrypt(value);
					userAllowedLimits = StringUtils.egTokenizer(value,"#");
					break;
				}
			}
		}
		return userAllowedLimits;
	}

%>


