<%
/*******************************************************************************
*	Name            :       UserLicenseJSON.jsp
*	Purpose         :       To View User License Settings (Default/Specific)
*	author			:		Meena.V
*	Created	on		:		15-Feb-2017
*******************************************************************************/
%>

<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.eg.EgCertUsage"%>
<%@ page import = "com.eg.EgUsersInfo"%>
<%@ page import = "com.eg.EgUuidInfo"%>
<%@ page import = "com.egurkha.User"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "java.sql.*"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import = "java.text.SimpleDateFormat" %>

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>

<%
	JSONObject rootJson = new JSONObject();

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

	String unlimited = "Unlimited";
	String defaultUsername = "eGDefault";
	String totMonDefault = "";
	String premiumMonDefault = "";
	String basicMonDefault = "";
	String networkDevDefault = "";
	String isMgrUsedBased = "false";
	String concUsers = "";
	String namedUsers = "";
	String usersDefCount = "";

	boolean isMspModel = EgUuidInfo.isMspModel();
	boolean isMgrConcUserBased = EgInstallInfo.isconcurrentUserLicense;
	boolean isMgrNamedUserBased = EgInstallInfo.isnamedUserLicense;
	long mgrConcUserCount = EgInstallInfo.allowedConcUsers;
	long mgrNamedUserCount = EgInstallInfo.allowedNamedUsers;

	if (isMgrConcUserBased || isMgrNamedUserBased)
	{
		isMgrUsedBased = "true";
	}

	String loginId = _user.getLoginID();
	EgUuidInfo uuidInfo = new EgUuidInfo();
	EgCertUsage user = new EgCertUsage();
	EgRoleInfo roleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	ArrayList usersList = user.getAllLimitedCompAccessUsers(true);
	boolean isLimitedAdmin = (usersList.contains(_user.getLoginID()));
	ArrayList orgsList = new ArrayList();
	ArrayList defOrgDefUsersList = User.getDefaultUsers();
	Hashtable orgMaps = uuidInfo.getSuperSubOrgMapping();
	String superOrg = (!uuidInfo.isSuperOrg(loginId)) ? uuidInfo.getSuperOU(loginId) : loginId;
	if (isLimitedAdmin)
	{
		orgsList = new ArrayList(uuidInfo.getDirectSubOU(loginId));
	}
	else
	{
		if (isMspModel)
		{
			Enumeration en = orgMaps.keys();
			while (en.hasMoreElements())
			{
				orgsList.add((String)en.nextElement());
			}
		}
		else
		{
			orgsList = new ArrayList(uuidInfo.getDirectSubOU("egenterprise"));
		}
	}

	//getting total license count of manager
	CertValidator cert = new CertValidator();
	egurkha.UserBean userBean = new egurkha.UserBean();
	int totalMonitorsCount = cert.getAllowedTotalCount();
	int basicMonitorsCount = cert.getAllowedBasicCount();
	int PremiumMonitorsCount = cert.getAllowedPremiumCount();
	int networkMonitorsCount = cert.getAllowedNetworkDevicesCount();
	int userBasedCount = 0;
	int monitorUsersCount = EgMemInfo.users;

	EgUsersInfo obj = new EgUsersInfo();
	ArrayList aListData = null;
	if(isMgrUsedBased.equalsIgnoreCase("true"))
	{
		String count = "0";
		String AllowedCount = isMgrConcUserBased ? String.valueOf(mgrConcUserCount) : String.valueOf(mgrNamedUserCount);
		String avail_count = AllowedCount;
		double avail = 0.0;

		aListData = obj.getRemoteUserCount();
		if (aListData == null || aListData.size() ==0)
		{
			aListData = obj.getRemoteUserCount(true);
		}
		if(aListData != null && aListData.size()>0)
		{
			count = (String)aListData.get(0);
			AllowedCount = (String)aListData.get(1);
		}
		
		if (!AllowedCount.equals("-") && !AllowedCount.equals("-1"))
		{
			userBasedCount = Integer.parseInt(AllowedCount);
		}
		else
		{
			userBasedCount = -1;
		}
		if(isMgrConcUserBased)
		{
			concUsers = (AllowedCount.equals("-") || AllowedCount.equals("-1")) ? unlimited : avail_count;
			rootJson.put("userBasedCount",concUsers);
		}
		else if(isMgrNamedUserBased)
		{
			namedUsers = (AllowedCount.equals("-") && AllowedCount.equals("-1")) ? unlimited : avail_count;
			rootJson.put("userBasedCount",namedUsers);
		}
	}

	//Getting used count details of given username (OU/org)
	String userName = (String)request.getParameter("userName");
	if (userName != null && userName.length() > 0)
	{
		user.setUserName(userName);
		String usedCountDetails = "";
		HashMap detailsMap = new HashMap();
		// Total monitors
		detailsMap = user.getTotalMonitorsDetailsForUser();
		String used = (String)detailsMap.get("Used");
		usedCountDetails += used+"#";

		//Premium monitors and Basic monitors
		detailsMap = user.getPremiumMonitorsDetailsForUser();
		String usedPrem = (String)detailsMap.get("Used");
		int usedPremium = Integer.parseInt(usedPrem);
		detailsMap = user.getBasicMonitorsDetailsForUser();
		String usedBas = (String)detailsMap.get("Used");
		int usedBasic = Integer.parseInt(usedBas);
		//If basic comps exceeds the allowed count then it will consume premium license if exist.
		GroupCertValidator grpCert = new GroupCertValidator(userName);
		boolean hasManagerLicCount = !grpCert.allowLicenseCheckForUser();
		String usersBasicAllowedCnt = (hasManagerLicCount) ? String.valueOf(basicMonitorsCount) : grpCert.totalBasicStr;
		if (!usersBasicAllowedCnt.equals("-1"))
		{
			int allowedBas = Integer.parseInt(usersBasicAllowedCnt);
			if (usedBasic > allowedBas)
			{
				usedPremium += (usedBasic-allowedBas);
				usedBasic  = allowedBas;
				usedPrem = String.valueOf(usedPremium);
				usedBas = String.valueOf(usedBasic);
			}
		}
		usedCountDetails += usedPrem+"#"+usedBas+"#";

		//Network Devices
		detailsMap = user.getNetworkDevicesDetailsForUser();
		used = (String)detailsMap.get("Used");
		usedCountDetails += used+"#";

		//Monitor Users
		ArrayList usersUnderOU = uuidInfo.getAllSubOrgsAndUsers(userName);
		used = "0";
		if (usersUnderOU != null && usersUnderOU.size() > 0)
		{
			usersUnderOU.remove(userName);
			used = String.valueOf(usersUnderOU.size());
		}
		usedCountDetails += used+"#";
		usedCountDetails = usedCountDetails.substring(0,(usedCountDetails.length()-1));
		rootJson.put("usedLicCountDetails",usedCountDetails);
		//rootJson.put("success","true");

		//if (request.getQueryString() != null)
		//{
			//session.setAttribute("adminLastAccessedURL","/final/admin/EgUserLicense.jsp?"+request.getQueryString());
		//}
		//else
		//{
			//session.setAttribute("adminLastAccessedURL","/final/admin/EgUserLicense.jsp");
		//}
		//out.println(rootJson.toString());
		//return;
	}

	/**
	 * To get non expired limited admin access users list
	 */
	ArrayList expiredUserList = new ArrayList();
	EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
	try
	{
		String str_conn = egDb.setConnection();
		ResultSet rs = egDb.selectValidityPeriod();
		while(rs.next())
		{
			String user_id = rs.getString("user_id");
			long days = rs.getLong("days");
			if(days < 0)
			{
				expiredUserList.add(user_id);
			}
		}
		if (rs != null)
			rs.close();
	}
	catch(Exception e)
	{
		egDb.releaseConnection(true);
		EgDbAdapterTypeUI.releaseObject(egDb);
		e.printStackTrace();
	}
	egDb.releaseConnection(true);
	EgDbAdapterTypeUI.releaseObject(egDb);
	usersList.removeAll(expiredUserList);

	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));

	Hashtable allOrgsAndUserMap = uuidInfo.getSuperSubOrgMapping();
	ArrayList orgUserList = new ArrayList();
	if (isMspModel)
	{
		IniFile uuidIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_uuid.ini");
		String[] orgVars = uuidIni.getVariables("ORG_UUID");
		int orgVarLen = (orgVars != null) ? orgVars.length : 0;
		for (int b=0; b<orgVarLen; b++)
		{
			String orgVar = orgVars[b];
			ArrayList tempList = (ArrayList)allOrgsAndUserMap.get(orgVar);
			if (!orgVar.equalsIgnoreCase("egenterprise"))
			{
				orgUserList.add(orgVar);
			}
			if (tempList != null && tempList.size() > 0)
			{
				orgUserList.addAll(tempList);
			}
		}
	}
	else
	{
		orgUserList = (ArrayList)allOrgsAndUserMap.get(superOrg);
	}
	if (isLimitedAdmin)
	{
		
		String name = uuidInfo.isOrg(loginId) ? loginId : uuidInfo.getDirectDependentOU(loginId);
		TreeSet subOUsList = uuidInfo.getAllUsersUnderOrg(name);
		if (uuidInfo.isOrg(loginId))
		{
			subOUsList.add(loginId);
		}
		if (subOUsList != null)
		{
			orgUserList = new ArrayList();
			Iterator itrOU = subOUsList.iterator();
			while (itrOU.hasNext())
			{
				String OU_Name = (String)itrOU.next();
				if (uuidInfo.isUser(OU_Name))
				{
					continue;
				}
				orgUserList.add(OU_Name);
			}
		}
	}

	IniFile egMgrMisc = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
	
	String defaultValue ="";
	String[] vars = {"TotalMonitors","BasicMonitors","NetworkDevices","UserBased","MonitorUsers"};
	for(int v=0; v<vars.length; v++)
	{
		String temp = egMgrMisc.getValue("DEFAULT_LICENSING_POLICY",vars[v]);
		defaultValue+= temp+"#";
	}
	if (defaultValue != null && !defaultValue.equals(""))
	{
		defaultValue = defaultValue.substring(0,defaultValue.length()-1);
	}
	
	boolean disableDelete = true;
	if(orgUserList!=null &&orgUserList.size()!=0)
	{
		Iterator ittt = orgUserList.iterator();
		while(ittt.hasNext())
		{
			String org =(String) ittt.next(); 
			String value = userCompMapIni.getValue("Users_Allowed_Count",org);
			value = EgCrypt.decrypt(value);
			if(!value.equals(defaultValue))
			{
				disableDelete = false;
				break;
			}
		}
	}
		rootJson.put("disableDelAllBtn",disableDelete);

	//	availUsersList.retainAll(orgUserList);
	//	if (availUsersList == null || availUsersList.size() == 0)
	//	{
	//		rootJson.put("disableDelAllBtn",true);
	//	}
	//	else
	//	{
	//		rootJson.put("disableDelAllBtn",false);
	//	}

	//To show organization/organizational unit tree grid
	EgUserRole usrRole = _user.getUserRole();
	boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();
	String session_userid = (String)session.getAttribute("sess_userid");
	Hashtable specificOrgsAndUsersMap = getSpecificOrgsandUserList(orgUserList);

	ArrayList mgrLicDetails = new ArrayList();
	mgrLicDetails.add(String.valueOf(totalMonitorsCount));
	mgrLicDetails.add(String.valueOf(basicMonitorsCount));
	mgrLicDetails.add(String.valueOf(PremiumMonitorsCount));
	mgrLicDetails.add(String.valueOf(networkMonitorsCount));
	mgrLicDetails.add(String.valueOf(userBasedCount));
	mgrLicDetails.add(String.valueOf(monitorUsersCount));

	EgUserPermission sas = EgUserPermission.getInstance();
	if (usrRole.hasAllComponentAccess() && (usrRole.getAdminPerm() == 9223372036854775807L || usrRole.getAdminPerm() == sas.getAdminAllPermissionValue()))
	{
		rootJson.put("showConfDefaultLicenseBtn",true);
	}
	else
	{
		rootJson.put("showConfDefaultLicenseBtn",false);
	}

	//If logged in as full admin access user, then following block will be executed.
	if (hasAllComponentAccess)
	{
		//If it is 'saas' model, then the following block will be executed.
		if(isMspModel)
		{
			IniFile inifile1 = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_uuid.ini");
			String topLevelOrgs[] = inifile1.getVariables("ORG_UUID");
			ArrayList superOrgs = new ArrayList();
			if(topLevelOrgs != null && topLevelOrgs.length>0)
			{
				superOrgs.addAll(Arrays.asList(topLevelOrgs));
			}

			JSONArray exportDataArr = new JSONArray();
			JSONObject exportDataObj = new JSONObject();

			for(int i=0;i<superOrgs.size();i++)
			{
				exportDataObj = new JSONObject();
				String optVar = "";
				String optVal = "";

				String strDbChild = "";
				String orgTotMon = "", orgBasicMon = "", orgPremiumMon = "", orgNetworkDev = "", orgConcUsers = "", orgNamedUsers = "", orgUsersBased = "", orgUsersCount = "";

				String orgname = (String)superOrgs.get(i);
				optVar = (String)superOrgs.get(i);
				optVal = (String)superOrgs.get(i);

				String displayName = optVal;
				if (optVal.startsWith("samlsso/"))
				{
					int idx = optVal.indexOf("/");
					displayName = optVal.substring(idx+1) + " (SAML)";
				}
				else if (optVal.indexOf("/") != -1)
				{
					if (optVal.indexOf("/Grp/") != -1)
					{
						String grpDelimiter = "/Grp/";
						int idx = optVal.indexOf(grpDelimiter);
						String str_uname_A = optVal.substring(0,idx);
						int nextIdx = idx + grpDelimiter.length();
						String str_uname_B = optVal.substring(nextIdx);
						displayName = str_uname_A + "/" + str_uname_B + " (Group)";
					}
				}
				//for super org datas (Organization)
				if (optVar.equalsIgnoreCase("egenterprise"))
				{
					exportDataObj.put("UserID",_mapping.getTextDescription("admin.user.egenterprise"));
				}
				else
				{
					exportDataObj.put("UserID",displayName);
				}
				exportDataObj.put("id",optVar);
				exportDataObj.put("iconCls","iconDomain");
				exportDataObj.put("expanded",true);

				boolean disableModifyIcon = false;
				boolean disableDeleteIcon = false;
				if((isLimitedAdmin && orgname.equals(loginId)) || (isMspModel && orgname.equalsIgnoreCase("egenterprise")))
				{
					disableModifyIcon = true;
					disableDeleteIcon = true;
				}
				//if (!availUsersList.contains(orgname))
				if (defaultValue != null && !defaultValue.equals(""))
				{
					String value = userCompMapIni.getValue("Users_Allowed_Count",orgname);
					value = EgCrypt.decrypt(value);
					if(value.equals(defaultValue))
					{
						disableDeleteIcon = true;
					}
				}
				exportDataObj.put("disableModify",disableModifyIcon);
				exportDataObj.put("disableDelete",disableDeleteIcon);

				//Getting license count values of user/organizational unit.
				String totMonDef = String.valueOf(totalMonitorsCount);
				String basicMonDef = String.valueOf(basicMonitorsCount);
				String networkDevDef = String.valueOf(networkMonitorsCount);
				String premiumMonDef = String.valueOf(PremiumMonitorsCount);
				String userBasedDef = String.valueOf(userBasedCount);
				String userCntDef = String.valueOf(monitorUsersCount);
				ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgname);
				if (userAllowedLimits != null && userAllowedLimits.size() > 0)
				{
					totMonDef = userAllowedLimits.get(0).toString();
					basicMonDef = userAllowedLimits.get(1).toString();
					networkDevDef = userAllowedLimits.get(2).toString();
					if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
					{
						userBasedDef = userAllowedLimits.get(3).toString();
						userCntDef = userAllowedLimits.get(4).toString();
					}
					else
					{
						userBasedDef = "0";
						userCntDef = userAllowedLimits.get(3).toString();
					}
					int allowedTotalCnt = Integer.parseInt(totMonDef);
					int allowedBasicCnt = Integer.parseInt(basicMonDef);
					int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
					premiumMonDef = String.valueOf(allowedPremuCnt);
				}

				totMonDef = totMonDef.equals("-1") ? unlimited : totMonDef;
				
				if( !totMonDef.equalsIgnoreCase("unlimited") && Integer.parseInt(totMonDef) > -1 &&  Integer.parseInt(basicMonDef) == -1)
				{
					basicMonDef = "-";
				}
				else
				{
					basicMonDef = basicMonDef.equals("-1") ? unlimited : basicMonDef;
				}
				networkDevDef = networkDevDef.equals("-1") ? unlimited : networkDevDef;
				premiumMonDef = premiumMonDef.equals("-1") ? unlimited : premiumMonDef;
				userBasedDef = userBasedDef.equals("-1") ? unlimited : userBasedDef;
				userCntDef = userCntDef.equals("-1") ? unlimited : userCntDef;

				//Getting license count values of organizational unit/organization.
				String orgUsersName = (String)specificOrgsAndUsersMap.get(orgname);
				String totMonSpecific = String.valueOf(totalMonitorsCount);
				String basicMonSpecific = String.valueOf(basicMonitorsCount);
				String networkDevSpecific = String.valueOf(networkMonitorsCount);
				String premiumMonSpecific = String.valueOf(PremiumMonitorsCount);
				String usersBasedSpecific = String.valueOf(userBasedCount);
				String usersCountSpecific = String.valueOf(monitorUsersCount);

				ArrayList orgAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgUsersName);
				if (orgAllowedLimits != null && orgAllowedLimits.size() > 0)
				{
					totMonSpecific = orgAllowedLimits.get(0).toString();
					basicMonSpecific = orgAllowedLimits.get(1).toString();
					networkDevSpecific = orgAllowedLimits.get(2).toString();
					if (isMgrUsedBased.equalsIgnoreCase("true") || orgAllowedLimits.size()==5)
					{
						usersBasedSpecific = orgAllowedLimits.get(3).toString();
						usersCountSpecific = orgAllowedLimits.get(4).toString();
					}
					else
					{
						usersBasedSpecific = "0";
						usersCountSpecific = orgAllowedLimits.get(3).toString();
					}
					int allowedTotalCnt = Integer.parseInt(totMonSpecific);
					int allowedBasicCnt = Integer.parseInt(basicMonSpecific);
					int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
					premiumMonSpecific = String.valueOf(allowedPremuCnt);
				}

				totMonSpecific = totMonSpecific.equals("-1") ? unlimited : totMonSpecific;
				basicMonSpecific = basicMonSpecific.equals("-1") ? unlimited : basicMonSpecific;
				networkDevSpecific = networkDevSpecific.equals("-1") ? unlimited : networkDevSpecific;
				premiumMonSpecific = premiumMonSpecific.equals("-1") ? unlimited : premiumMonSpecific;
				usersBasedSpecific = usersBasedSpecific.equals("-1") ? unlimited : usersBasedSpecific;
				usersCountSpecific = usersCountSpecific.equals("-1") ? unlimited : usersCountSpecific;

				orgTotMon = totMonDef + "#" + totMonSpecific;
				orgBasicMon = basicMonDef + "#" + basicMonSpecific;
				orgNetworkDev = networkDevDef + "#" + networkDevSpecific;
				orgPremiumMon = premiumMonDef + "#" + premiumMonSpecific;
				orgUsersBased = userBasedDef + "#" + usersBasedSpecific;
				orgUsersCount = userCntDef + "#" + usersCountSpecific;
				exportDataObj.put("TotalMonitors",orgTotMon);
				exportDataObj.put("BasicMonitors",orgBasicMon);
				exportDataObj.put("NetworkDevices",orgNetworkDev);
				exportDataObj.put("PremiumMonitors",orgPremiumMon);
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					exportDataObj.put("UserBased",orgUsersBased);
				}
				exportDataObj.put("UserCount",orgUsersCount);

				//for sub org datas (Organizational unit)
				JSONArray rootUserObjectArray = uuidInfo.buildOULicenseTreeJson(orgname,false,specificOrgsAndUsersMap,isLimitedAdmin,loginId,mgrLicDetails,defaultValue);
				if (!rootUserObjectArray.isEmpty())
				{
					exportDataObj.put("children",rootUserObjectArray);
				}

				exportDataArr.add(exportDataObj);
			}
			rootJson.put("exportDataArr",exportDataArr);

			if (exportDataArr.isEmpty())
			{
				rootJson.put("isUsersCreated",new Boolean(false));
				out.println(rootJson);
				return;
			}
		}
		else //If it is 'enterprise' model, then the following block will be executed.
		{
			JSONArray exportDataArr = new JSONArray();
			JSONObject exportDataObj = new JSONObject();
			String orgname = "egenterprise";
			String orgTotMon = "", orgBasicMon = "", orgPremiumMon = "", orgNetworkDev = "", orgConcUsers = "", orgNamedUsers = "", orgUsersBased = "", orgUsersCount = "";

			//for super org datas (Organizatio)
			if (orgname.equalsIgnoreCase("egenterprise"))
			{
				exportDataObj.put("UserID",_mapping.getTextDescription("admin.user.egenterprise"));
			}
			else
			{
				exportDataObj.put("UserID",orgname);
			}
			exportDataObj.put("id",orgname);
			exportDataObj.put("iconCls","iconDomain");
			exportDataObj.put("expanded",true);

			boolean disableModifyIcon = true;
			boolean disableDeleteIcon = false;
			//if (availUsersList.contains(orgname))
			if (defaultValue != null && !defaultValue.equals(""))
			{
				String value = userCompMapIni.getValue("Users_Allowed_Count",orgname);
				value = EgCrypt.decrypt(value);
				if(value.equals(defaultValue))
				{
					disableDeleteIcon = true;
				}
			}
			exportDataObj.put("disableModify",disableModifyIcon);
			exportDataObj.put("disableDelete",disableDeleteIcon);

			//Getting license count values of user/organizational unit.
			String totMonDef = String.valueOf(totalMonitorsCount);
			String basicMonDef = String.valueOf(basicMonitorsCount);
			String networkDevDef = String.valueOf(networkMonitorsCount);
			String premiumMonDef = String.valueOf(PremiumMonitorsCount);
			String userBasedDef = String.valueOf(userBasedCount);
			String userCntDef = String.valueOf(monitorUsersCount);
			ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgname);
			if (userAllowedLimits != null && userAllowedLimits.size() > 0)
			{
				totMonDef = userAllowedLimits.get(0).toString();
				basicMonDef = userAllowedLimits.get(1).toString();
				networkDevDef = userAllowedLimits.get(2).toString();
				if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
				{
					userBasedDef = userAllowedLimits.get(3).toString();
					userCntDef = userAllowedLimits.get(4).toString();
				}
				else
				{
					userBasedDef = "0";
					userCntDef = userAllowedLimits.get(3).toString();
				}
				int allowedTotalCnt = Integer.parseInt(totMonDef);
				int allowedBasicCnt = Integer.parseInt(basicMonDef);
				int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
				premiumMonDef = String.valueOf(allowedPremuCnt);
			}

			totMonDef = totMonDef.equals("-1") ? unlimited : totMonDef;
			if(!totMonDef.equalsIgnoreCase("unlimited") && Integer.parseInt(totMonDef) > -1 &&  Integer.parseInt(basicMonDef) == -1)
			{
				basicMonDef = "-";
			}
			else
			{
				basicMonDef = basicMonDef.equals("-1") ? unlimited : basicMonDef;
			}
			networkDevDef = networkDevDef.equals("-1") ? unlimited : networkDevDef;
			premiumMonDef = premiumMonDef.equals("-1") ? unlimited : premiumMonDef;
			userBasedDef = userBasedDef.equals("-1") ? unlimited : userBasedDef;
			userCntDef = userCntDef.equals("-1") ? unlimited : userCntDef;

			//Getting license count values of organizational unit/organization.
			String orgUsersName = (String)specificOrgsAndUsersMap.get(orgname);
			String totMonSpecific = String.valueOf(totalMonitorsCount);
			String basicMonSpecific = String.valueOf(basicMonitorsCount);
			String networkDevSpecific = String.valueOf(networkMonitorsCount);
			String premiumMonSpecific = String.valueOf(PremiumMonitorsCount);
			String usersBasedSpecific = String.valueOf(userBasedCount);
			String usersCountSpecific = String.valueOf(monitorUsersCount);
			ArrayList orgAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgUsersName);
			if (orgAllowedLimits != null && orgAllowedLimits.size() > 0)
			{
				totMonSpecific = orgAllowedLimits.get(0).toString();
				basicMonSpecific = orgAllowedLimits.get(1).toString();
				networkDevSpecific = orgAllowedLimits.get(2).toString();
				if (isMgrUsedBased.equalsIgnoreCase("true") || orgAllowedLimits.size()==5)
				{
					usersBasedSpecific = orgAllowedLimits.get(3).toString();
					usersCountSpecific = orgAllowedLimits.get(4).toString();
				}
				else
				{
					usersBasedSpecific = "0";
					usersCountSpecific = orgAllowedLimits.get(3).toString();
				}
				int allowedTotalCnt = Integer.parseInt(totMonSpecific);
				int allowedBasicCnt = Integer.parseInt(basicMonSpecific);
				int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
				premiumMonSpecific = String.valueOf(allowedPremuCnt);
			}

			totMonSpecific = totMonSpecific.equals("-1") ? unlimited : totMonSpecific;
			basicMonSpecific = basicMonSpecific.equals("-1") ? unlimited : basicMonSpecific;
			networkDevSpecific = networkDevSpecific.equals("-1") ? unlimited : networkDevSpecific;
			premiumMonSpecific = premiumMonSpecific.equals("-1") ? unlimited : premiumMonSpecific;
			usersBasedSpecific = usersBasedSpecific.equals("-1") ? unlimited : usersBasedSpecific;
			usersCountSpecific = usersCountSpecific.equals("-1") ? unlimited : usersCountSpecific;

			orgTotMon = totMonDef + "#" + totMonSpecific;
			orgBasicMon = basicMonDef + "#" + basicMonSpecific;
			orgNetworkDev = networkDevDef + "#" + networkDevSpecific;
			orgPremiumMon = premiumMonDef + "#" + premiumMonSpecific;
			orgUsersBased = userBasedDef + "#" + usersBasedSpecific;
			orgUsersCount = userCntDef + "#" + usersCountSpecific;
			exportDataObj.put("TotalMonitors",orgTotMon);
			exportDataObj.put("BasicMonitors",orgBasicMon);
			exportDataObj.put("NetworkDevices",orgNetworkDev);
			exportDataObj.put("PremiumMonitors",orgPremiumMon);
			if (isMgrUsedBased.equalsIgnoreCase("true"))
			{
				exportDataObj.put("UserBased",orgUsersBased);
			}
			exportDataObj.put("UserCount",orgUsersCount);

			//for sub org datas (Organizational unit)
			JSONArray rootUserObjectArray = uuidInfo.buildOULicenseTreeJson(orgname,false,specificOrgsAndUsersMap,isLimitedAdmin,loginId,mgrLicDetails,defaultValue);
			if (!rootUserObjectArray.isEmpty())
			{
				exportDataObj.put("children",rootUserObjectArray);
			}

			exportDataArr.add(exportDataObj);
			rootJson.put("exportDataArr",exportDataArr);
		}
	}
	else //If logged in as limited admin access user, then following block will be executed.
	{
		String orgname = "";
		boolean isSuperOrg = uuidInfo.isSuperOrg(session_userid);
		boolean isOrg = uuidInfo.isOrg(session_userid);
		if (isSuperOrg)
		{
			orgname = session_userid;
		}
		else if (isOrg)
		{
			orgname = session_userid;
		}
		else
		{
			orgname = uuidInfo.getDirectDependentOU(session_userid);
		}

		JSONArray exportDataArr = new JSONArray();
		JSONObject exportDataObj = new JSONObject();
		String orgTotMon = "", orgBasicMon = "", orgPremiumMon = "", orgNetworkDev = "", orgConcUsers = "", orgNamedUsers = "", orgUsersBased = "", orgUsersCount = "";
		String displayName = orgname;
		if (orgname.startsWith("samlsso/"))
		{
			int idx = orgname.indexOf("/");
			displayName = orgname.substring(idx+1) + " (SAML)";
		}
		else if (orgname.indexOf("/") != -1)
		{
			if (orgname.indexOf("/Grp/") != -1)
			{
				String grpDelimiter = "/Grp/";
				int idx = orgname.indexOf(grpDelimiter);
				String str_uname_A = orgname.substring(0,idx);
				int nextIdx = idx + grpDelimiter.length();
				String str_uname_B = orgname.substring(nextIdx);
				displayName = str_uname_A + "/" + str_uname_B + " (Group)";
			}
		}

		//for super org datas (Organization)
		if (orgname.equalsIgnoreCase("egenterprise"))
		{
			exportDataObj.put("UserID",_mapping.getTextDescription("admin.user.egenterprise"));
		}
		else
		{
			exportDataObj.put("UserID",displayName);
		}
		exportDataObj.put("id",orgname);

		if (isSuperOrg)
		{
			exportDataObj.put("iconCls","iconDomain");
		}
		else
		{
			exportDataObj.put("iconCls","iconOtherUsers");
		}
		exportDataObj.put("expanded",true);

		boolean disableModifyIcon = false;
		boolean disableDeleteIcon = false;
		if((isLimitedAdmin && (orgname.equals(loginId) || (uuidInfo.isUser(loginId) && uuidInfo.hasOURole(loginId)))) || (isMspModel && orgname.equalsIgnoreCase("egenterprise")))
		{
			disableModifyIcon = true;
			disableDeleteIcon = true;
		}
		//if (!availUsersList.contains(orgname))
		if (defaultValue != null && !defaultValue.equals(""))
		{
			String value = userCompMapIni.getValue("Users_Allowed_Count",orgname);
			value = EgCrypt.decrypt(value);
			if(value.equals(defaultValue))
			{
				disableDeleteIcon = true;
			}
		}
		exportDataObj.put("disableModify",disableModifyIcon);
		exportDataObj.put("disableDelete",disableDeleteIcon);

		//Getting license count values of user/organizational unit.
		String totMonDef = String.valueOf(totalMonitorsCount);
		String basicMonDef = String.valueOf(basicMonitorsCount);
		String networkDevDef = String.valueOf(networkMonitorsCount);
		String premiumMonDef = String.valueOf(PremiumMonitorsCount);
		String userBasedDef = String.valueOf(userBasedCount);
		String userCntDef = String.valueOf(monitorUsersCount);
		ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgname);
		if (userAllowedLimits != null && userAllowedLimits.size() > 0)
		{
			totMonDef = userAllowedLimits.get(0).toString();
			basicMonDef = userAllowedLimits.get(1).toString();
			networkDevDef = userAllowedLimits.get(2).toString();
			if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
			{
				userBasedDef = userAllowedLimits.get(3).toString();
				userCntDef = userAllowedLimits.get(4).toString();
			}
			else
			{
				userBasedDef = "0";
				userCntDef = userAllowedLimits.get(3).toString();
			}
			int allowedTotalCnt = Integer.parseInt(totMonDef);
			int allowedBasicCnt = Integer.parseInt(basicMonDef);
			int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
			premiumMonDef = String.valueOf(allowedPremuCnt);
		}

		totMonDef = totMonDef.equals("-1") ? unlimited : totMonDef;
		if( !totMonDef.equalsIgnoreCase("unlimited") && Integer.parseInt(totMonDef) > -1 &&  Integer.parseInt(basicMonDef) == -1)
		{
			basicMonDef = "-";
		}
		else
		{
			basicMonDef = basicMonDef.equals("-1") ? unlimited : basicMonDef;
		}
		networkDevDef = networkDevDef.equals("-1") ? unlimited : networkDevDef;
		premiumMonDef = premiumMonDef.equals("-1") ? unlimited : premiumMonDef;
		userBasedDef = userBasedDef.equals("-1") ? unlimited : userBasedDef;
		userCntDef = userCntDef.equals("-1") ? unlimited : userCntDef;

		//Getting license count values of organizational unit/organization.
		String orgUsersName = (String)specificOrgsAndUsersMap.get(orgname);
		String totMonSpecific = String.valueOf(totalMonitorsCount);
		String basicMonSpecific = String.valueOf(basicMonitorsCount);
		String networkDevSpecific = String.valueOf(networkMonitorsCount);
		String premiumMonSpecific = String.valueOf(PremiumMonitorsCount);
		String usersBasedSpecific = String.valueOf(userBasedCount);
		String usersCountSpecific = String.valueOf(monitorUsersCount);

		ArrayList orgAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgUsersName);
		if (orgAllowedLimits != null && orgAllowedLimits.size() > 0)
		{
			totMonSpecific = orgAllowedLimits.get(0).toString();
			basicMonSpecific = orgAllowedLimits.get(1).toString();
			networkDevSpecific = orgAllowedLimits.get(2).toString();
			if (isMgrUsedBased.equalsIgnoreCase("true") || orgAllowedLimits.size()==5)
			{
				usersBasedSpecific = orgAllowedLimits.get(3).toString();
				usersCountSpecific = orgAllowedLimits.get(4).toString();
			}
			else
			{
				usersBasedSpecific = "0";
				usersCountSpecific = orgAllowedLimits.get(3).toString();
			}
			int allowedTotalCnt = Integer.parseInt(totMonSpecific);
			int allowedBasicCnt = Integer.parseInt(basicMonSpecific);
			int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
			premiumMonSpecific = String.valueOf(allowedPremuCnt);
		}

		totMonSpecific = totMonSpecific.equals("-1") ? unlimited : totMonSpecific;
		basicMonSpecific = basicMonSpecific.equals("-1") ? unlimited : basicMonSpecific;
		networkDevSpecific = networkDevSpecific.equals("-1") ? unlimited : networkDevSpecific;
		premiumMonSpecific = premiumMonSpecific.equals("-1") ? unlimited : premiumMonSpecific;
		usersBasedSpecific = usersBasedSpecific.equals("-1") ? unlimited : usersBasedSpecific;
		usersCountSpecific = usersCountSpecific.equals("-1") ? unlimited : usersCountSpecific;

		orgTotMon = totMonDef + "#" + totMonSpecific;
		orgBasicMon = basicMonDef + "#" + basicMonSpecific;
		orgNetworkDev = networkDevDef + "#" + networkDevSpecific;
		orgPremiumMon = premiumMonDef + "#" + premiumMonSpecific;
		orgUsersBased = userBasedDef + "#" + usersBasedSpecific;
		orgUsersCount = userCntDef + "#" + usersCountSpecific;
		exportDataObj.put("TotalMonitors",orgTotMon);
		exportDataObj.put("BasicMonitors",orgBasicMon);
		exportDataObj.put("NetworkDevices",orgNetworkDev);
		exportDataObj.put("PremiumMonitors",orgPremiumMon);
		if (isMgrUsedBased.equalsIgnoreCase("true"))
		{
			exportDataObj.put("UserBased",orgUsersBased);
		}
		exportDataObj.put("UserCount",orgUsersCount);

		//for sub org datas (Organizational unit)
		JSONArray rootUserObjectArray = uuidInfo.buildOULicenseTreeJson(orgname,false,specificOrgsAndUsersMap,isLimitedAdmin,loginId,mgrLicDetails,defaultValue);
		if (!rootUserObjectArray.isEmpty())
		{
			exportDataObj.put("children",rootUserObjectArray);
		}

		exportDataArr.add(exportDataObj);
		rootJson.put("exportDataArr",exportDataArr);
	}

	//getting used license count of manager
	egurkha.UserBean userbean = new egurkha.UserBean();
	int used_basic = userbean.getBasicMonitorsCount();
	int used_Premium = userbean.getPremiumMonitorsCount();
	int used_total = used_basic + used_Premium;
	int used_extAgents = userbean.getNetDeviceCount();
	int used_usr_count = 0;//userbean.monUserCount();
	if(userbean.setConnection().equalsIgnoreCase("CONNECTED"))
	{
		used_usr_count = userbean.monUserCount();
	}
	userbean.releaseConnection(false);

	//calculating available license count of manager
	int availBasic = 0, availPremium = 0, availTotal = 0, availNetwork = 0, availUsersCount = 0;
	if(basicMonitorsCount > -1)
	{
		if(used_basic <= basicMonitorsCount)
		{
			availBasic = basicMonitorsCount - used_basic;
		}
		basicMonDefault = String.valueOf(availBasic);
	}
	else
	{
		basicMonDefault = unlimited;
	}

	if(PremiumMonitorsCount > -1)
	{
		if(used_Premium <= PremiumMonitorsCount)
		{
			availPremium = PremiumMonitorsCount - used_Premium;
		}
		totMonDefault = String.valueOf(availTotal);
	}
	else
	{
		totMonDefault = unlimited;
	}

	if(totalMonitorsCount > -1)
	{
		availTotal = availBasic + availPremium;
		totMonDefault = String.valueOf(availTotal);
	}
	else
	{
		totMonDefault = unlimited;
	}

	if(networkMonitorsCount > -1)
	{
		if(used_extAgents <= networkMonitorsCount)
		{
			availNetwork = networkMonitorsCount - used_extAgents;
		}
		networkDevDefault = String.valueOf(availNetwork);
	}
	else
	{
		networkDevDefault = unlimited;
	}

	if (monitorUsersCount > -1)
	{
		if(used_usr_count <= monitorUsersCount)
		{
			availUsersCount = monitorUsersCount - used_usr_count;
		}
		usersDefCount = String.valueOf(availUsersCount);
	}
	else
	{
		usersDefCount = unlimited;
	}

	rootJson.put("totalMonitorsCount",totMonDefault);
	rootJson.put("premMonitorsCount",PremiumMonitorsCount);
	rootJson.put("basicMonitorsCount",basicMonDefault);
	rootJson.put("networkMonitorsCount",networkDevDefault);
	rootJson.put("totMonDefault",totMonDefault);
	rootJson.put("basicMonDefault",basicMonDefault);
	rootJson.put("networkDevDefault",networkDevDefault);
	rootJson.put("usersTotCount",usersDefCount);

	rootJson.put("isMgrUsedBased",isMgrUsedBased);
	rootJson.put("concUsers",concUsers);
	rootJson.put("namedUsers",namedUsers);
	rootJson.put("isMgrConcUserBased",isMgrConcUserBased);
	rootJson.put("isMgrNamedUserBased",isMgrNamedUserBased);
	rootJson.put("success","true");

	if (request.getQueryString() != null)
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/EgUserLicense.jsp?"+request.getQueryString());
	}
	else
	{
		session.setAttribute("adminLastAccessedURL","/final/admin/EgUserLicense.jsp");
	}
	out.println(rootJson.toString());
%>

<%!
	public Hashtable getSpecificOrgsandUserList(ArrayList availUsersList)
	{
		Hashtable resultMap = new Hashtable();
		EgUuidInfo egUuidObj = new EgUuidInfo();
		if(availUsersList != null)
		{
			int availLen = availUsersList.size();
			for (int k=0; k<availLen; k++)
			{
				String availStrUser = (String)availUsersList.get(k);
				String orgName = egUuidObj.getDirectDependentOU(availStrUser);
				if(orgName != null && orgName.length() > 0)
				{
					resultMap.put(availStrUser,orgName);
				}
				else if (egUuidObj.isSuperOrg(availStrUser))
				{
					resultMap.put(availStrUser,"-");
				}
			}
		}
		return resultMap;
	}

	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;
	}
%>



