<%
/**
 *	File name		:	LicenseUsageByOrgJson.jsp
 *	Purpose			:	This page provides overall report of organization/organizational unit license details
 */
%>

<%@ 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 = "java.util.Calendar"%>
<%@ page import = "java.util.Date"%>
<%@ page import = "java.math.*"%>
<%@ page import = "com.egurkha.util.DateUtil"%>
<%@ 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 rootJson = new JSONObject();

	EgCertUsage certUsage = new EgCertUsage();
	EgUserRole usrRole = _user.getUserRole();
	EgUuidInfo uuidInfo = new EgUuidInfo();
	EgUsersInfo usersInfo = new EgUsersInfo();
	EgRoleInfo egRoleInfo = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));
	boolean isLimitedAdmin = !egRoleInfo.hasAllComponentAccess();
	boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();
	boolean isMspModel = EgUuidInfo.isMspModel();
	String session_userid = (String)session.getAttribute("sess_userid");
	String loginId = _user.getLoginID();
	String isMgrUsedBased = "false";
	GroupCertValidator grpCert = null;

	boolean isCCUserCertEnabled = EgInstallInfo.isconcurrentUserLicense;
	boolean isNamedUserEnabled = EgInstallInfo.isnamedUserLicense;
	boolean isUserCertMgr = usersInfo.isUserBasedLicense();
	if (isCCUserCertEnabled || isNamedUserEnabled)
	{
		isMgrUsedBased = "true";
	}
	rootJson.put("isMgrUsedBased",isMgrUsedBased);

	//Named or CC users
	HashMap userCertInfo = new HashMap();
	ArrayList aListData = null;
//	ArrayList aListData1 = null;
	if(isUserCertMgr)
	{
		userCertInfo = certUsage.getCertUsersDetailsForUsers();
		
		aListData = usersInfo.getRemoteUserCount();
		//aListData1 = usersInfo.getUserInfos(false);
		if (aListData == null || aListData.size() ==0)
		{
			aListData = usersInfo.getRemoteUserCount(true);
		}
		//if (aListData1  == null || aListData1.size() == 0)
		//{
		//	aListData1 = usersInfo.getUserInfos();
		//}
		
	}

	//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 = (isMspModel) ? "License usage report by Organization/Organizational unit" : "License usage report by Organizational unit";
	String repDate = "Report generated on"+",\""+currDateStr+"\"";
	String colHeads =  (isMspModel) ? "Organization/Organizational unit" : "Organizational unit";
	String colSubHd = "";
	colHeads += ",,Total Monitors,,,Basic Monitors,,,Premium Monitors,,,Network Devices,,,";
	colSubHd += ",Allowed,Used,Available,Allowed,Used,Available,Allowed,Used,Available,Allowed,Used,Available";
	if (isUserCertMgr)
	{
		if (EgInstallInfo.isnamedUserLicense)
		{
			colHeads += "Named Users,,,,Monitor Users";
		}
		else
		{
			colHeads += "Concurrent Users,,,,Monitor Users";
		}
		colSubHd += ",Allowed,Used,Peak usage last month,Peak usage date,Allowed,Used,Available";
	}
	else
	{
		colHeads += "Monitor Users";
		colSubHd += ",Allowed,Used,Available";
	}

	csvData.add(repTitle);
	csvData.add(repDate);
	csvData.add("");
	csvData.add(colHeads);
	csvData.add(colSubHd);


	List csvDataList = new ArrayList();
	JSONArray exportDataArr = new JSONArray();
	JSONObject exportDataObj = new JSONObject();
	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";
	}

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

	//Manager License count
	CertValidator cert = new CertValidator();
	int mgrAllowedTotalCnt = cert.getAllowedTotalCount();
	int mgrAllowedBasicCnt = cert.getAllowedBasicCount();
	int mgrAllowedPremuCnt = cert.getAllowedPremiumCount();
	int mgrAllowedNwDevCnt = cert.getAllowedNetworkDevicesCount();
	int mgrAllowedMonUserCount = EgMemInfo.users;
	int mgrAllowedUserCount = 0;
	if(isCCUserCertEnabled)
	{
		mgrAllowedUserCount = (int)EgInstallInfo.allowedConcUsers;
	}
	else
	{
		mgrAllowedUserCount = (int)EgInstallInfo.allowedNamedUsers;
	}

	ArrayList mgrLicDetails = new ArrayList();
	GroupCertValidator grpCertVal = new GroupCertValidator("");
	mgrLicDetails.add(String.valueOf(mgrAllowedTotalCnt));
	mgrLicDetails.add(String.valueOf(mgrAllowedBasicCnt));
	mgrLicDetails.add(String.valueOf(mgrAllowedPremuCnt));
	mgrLicDetails.add(String.valueOf(mgrAllowedNwDevCnt));
	mgrLicDetails.add(String.valueOf(mgrAllowedUserCount));
	mgrLicDetails.add(String.valueOf(mgrAllowedMonUserCount));

	egurkha.UserBean user = new egurkha.UserBean();
	int used_total = user.getBasicMonitorsCount() + user.getPremiumMonitorsCount(); // Total used agents
	//If basic comps exceeds the allowed count then it will consume premium license if exist.
	int used_basic = user.getBasicMonitorsCount();
	int used_Premium = user.getPremiumMonitorsCount();
	if (mgrAllowedBasicCnt != -1)
	{
		int allowedBasic = mgrAllowedBasicCnt;
		if (used_basic > allowedBasic)
		{
			used_Premium += (used_basic-allowedBasic);
			used_basic  = allowedBasic;
		}
	}
	int used_network = user.getNetDeviceCount();
	int used_monUserCount = 0;
	if(user.setConnection().equalsIgnoreCase("CONNECTED"))
	{
		used_monUserCount = user.monUserCount();
	}
	user.releaseConnection(false);

	ArrayList mgrArrListData = null;
//	ArrayList mgrArrListData1 = null;
	String mgr_allowed_userBasedCount = "0", mgr_used_userBasedCount = "0", mgr_avail_userBasedCount = "0";
	String mgrPeakUsgCnt = "-", mgrPeakUsgDate = "-";
	IniFile egUI = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	String tmpValue = egUI.getValue("User_Cert","ShowUsersCountInUI");
	boolean showUsersCountInUI = (tmpValue != null && (tmpValue.equalsIgnoreCase("yes") || tmpValue.equalsIgnoreCase("true")));
	if (usersInfo.isUserBasedLicense() || showUsersCountInUI)
	{
		mgrArrListData = usersInfo.getRemoteUserCount();
	//	mgrArrListData1 = usersInfo.getUserInfos(false);
		if (mgrArrListData == null || mgrArrListData.size() ==0)
		{
			mgrArrListData = usersInfo.getRemoteUserCount(true);
		}
	//	if (mgrArrListData1  == null || mgrArrListData1.size() == 0)
	//	{
	//		mgrArrListData1 = usersInfo.getUserInfos();
	//	}
	}
	ArrayList peakUsageData = usersInfo.getPeakUsageValuesForPreviusMonth();
	if (peakUsageData != null && peakUsageData.size() >= 2)
	{
		String peakUsgCnt = peakUsageData.get(0).toString();
		String peakUsgDate = peakUsageData.get(1).toString();
		if (peakUsgCnt != null && peakUsgCnt.trim().length() > 0 && peakUsgDate != null && peakUsgDate.trim().length() > 0)
		{
			int dotIdx = peakUsgCnt.indexOf(".");
			if (dotIdx > -1)
			{
				peakUsgCnt = peakUsgCnt.substring(0,dotIdx);
			}
			peakUsgDate = com.egurkha.util.DateUtil.changeDateFormat(peakUsgDate,"yyyy-MM-dd HH:mm:ss",currDateFormat);
			mgrPeakUsgCnt = peakUsgCnt;
			mgrPeakUsgDate = peakUsgDate;
		}
	}
	if(mgrArrListData!=null && mgrArrListData.size()>0)
	{
		String count = (String)mgrArrListData.get(0);
		String AllowedCount = (String)mgrArrListData.get(1);
		double count_user = 0;
		double count_AllowedCount = 0;

		String count_user_str = "-";
		String count_AllowedCount_str = "-";
		String avail_str = "-";
		count_user = Double.parseDouble(count);
		count_user_str = Math.round(count_user)+"";
		if (!AllowedCount.equals("-"))
		{
			count_AllowedCount = Double.parseDouble(AllowedCount);
			count_AllowedCount_str = Math.round(count_AllowedCount)+"";
		}
		double avail = 0.0;
		if (!AllowedCount.equals("-"))
		{
			try{
				avail = Double.parseDouble(AllowedCount) - Double.parseDouble(count);
			}catch(Exception e){e.printStackTrace();}
			if (avail < 0.0)
			avail = 0.0;
			avail_str = Math.round(avail)+"";
		}
		mgr_allowed_userBasedCount = count_AllowedCount_str;
		mgr_used_userBasedCount = String.valueOf(count_user_str);
		mgr_avail_userBasedCount = String.valueOf(avail_str);
	}
	else if (usersInfo.isUserBasedLicense())
	{
		long getUserAllowedCount = usersInfo.getUserAllowedCount();
		mgr_allowed_userBasedCount = String.valueOf(getUserAllowedCount);
		mgr_used_userBasedCount = "0";
		mgr_avail_userBasedCount = String.valueOf(getUserAllowedCount);
	}
//	if(mgrArrListData1!=null && mgrArrListData1.size()>0)
//	{
//		for(int i=0;i<mgrArrListData1.size();i=i+4)
//		{
//			String strCompType = (String)mgrArrListData1.get(i);
//			String count = (String)mgrArrListData1.get(i+1);
//			String AllowedCount = (String)mgrArrListData1.get(i+2);
//			double count_user = Double.parseDouble(count);
//			mgr_allowed_userBasedCount = "-";
//			mgr_used_userBasedCount = String.valueOf(count_user);
//			mgr_avail_userBasedCount = "-";
//		}
//	}

	//To show organization/organizational unit tree grid
	
	//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)
		{
			exportDataArr = new JSONArray();
			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));
			}
			for(int i=0;i<superOrgs.size();i++)
			{
				exportDataObj = new JSONObject();
				String optVar = "";
				String optVal = "";

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

				//Getting allowed license count values of organization/organizational unit.
				String totMonOrg = String.valueOf(mgrAllowedTotalCnt);
				String basicMonOrg = String.valueOf(mgrAllowedBasicCnt);
				String premiumMonOrg = String.valueOf(mgrAllowedPremuCnt);
				String networkDevOrg = String.valueOf(mgrAllowedNwDevCnt);
				String userBasedOrg = String.valueOf(mgrAllowedUserCount);
				String userCntOrg = String.valueOf(mgrAllowedMonUserCount);
				ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgname);
				if (userAllowedLimits != null && userAllowedLimits.size() > 0)
				{
					totMonOrg = userAllowedLimits.get(0).toString();
					basicMonOrg = userAllowedLimits.get(1).toString();
					networkDevOrg = userAllowedLimits.get(2).toString();
					if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
					{
						userBasedOrg = userAllowedLimits.get(3).toString();
						userCntOrg = userAllowedLimits.get(4).toString();
					}
					else
					{
						userBasedOrg = "0";
						userCntOrg = userAllowedLimits.get(3).toString();
					}
					int allowedTotalCnt = Integer.parseInt(totMonOrg);
					int allowedBasicCnt = Integer.parseInt(basicMonOrg);
					int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
					premiumMonOrg = String.valueOf(allowedPremuCnt);
				}

				//Getting used and available license count values of organizational unit/organization.
				certUsage.setUserName(orgname);
				HashMap detailsMap = new HashMap();
				csvRow = orgname;

				//Total monitors
				int totCnt = Integer.parseInt(totMonOrg);
				int usedCnt = 0;
				String used = "0";
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					usedCnt = used_total;
					used = String.valueOf(usedCnt);
				}
				else
				{
					detailsMap = certUsage.getTotalMonitorsDetailsForUser();
					used = (String)detailsMap.get("Used");
					usedCnt = Integer.parseInt(used);
				}
				String availCnt = totMonOrg.equals("-1") ? "-" : String.valueOf(totCnt-usedCnt);
				totMonOrg = totMonOrg.equals("-1") ? "-" : totMonOrg;
				exportDataObj.put("totMons_TotalCnt",totMonOrg);
				exportDataObj.put("totMons_UsedCnt",used+"@#@"+orgname+"@#@Total Monitors");
				exportDataObj.put("totMons_AvailCnt",availCnt);
				csvRow += ","+totMonOrg+","+used+","+availCnt;

				//Premium monitors and Basic monitors
				int usedPremium = 0, usedBasic = 0;
				String usedPrem = "0", usedBas = "0";
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					usedPremium = used_Premium;
					usedPrem = String.valueOf(usedPremium);
					usedBasic = used_basic;
					usedBas = String.valueOf(usedBasic);
				}
				else
				{
					detailsMap = certUsage.getPremiumMonitorsDetailsForUser();
					usedPrem = (String)detailsMap.get("Used");
					usedPremium = Integer.parseInt(usedPrem);
					detailsMap = certUsage.getBasicMonitorsDetailsForUser();
					usedBas = (String)detailsMap.get("Used");
					usedBasic = Integer.parseInt(usedBas);
				}
				//If basic comps exceeds the allowed count then it will consume premium license if exist.
				if (!basicMonOrg.equals("-1"))
				{
					int allowedBas = Integer.parseInt(basicMonOrg);
					if (usedBasic > allowedBas)
					{
						usedPremium += (usedBasic-allowedBas);
						usedBasic  = allowedBas;
						usedPrem = String.valueOf(usedPremium);
						usedBas = String.valueOf(usedBasic);
					}
				}
				int basCnt = Integer.parseInt(basicMonOrg);
				int basicAvail = basCnt-usedBasic;
				if (basicAvail < 0)
				{
					basicAvail = 0;
				}
				availCnt = basicMonOrg.equals("-1") ? "-" : String.valueOf(basicAvail);
				basicMonOrg = basicMonOrg.equals("-1") ? "-" : basicMonOrg;
				exportDataObj.put("basMons_TotalCnt",basicMonOrg);
				exportDataObj.put("basMons_UsedCnt",usedBas+"@#@"+orgname+"@#@Basic Monitors");
				exportDataObj.put("basMons_AvailCnt",availCnt);
				csvRow += ","+basicMonOrg+","+usedBas+","+availCnt;

				int premCnt = totCnt - basCnt;
				availCnt = premiumMonOrg.equals("-1") ? "-" : String.valueOf(premCnt-usedPremium);
				premiumMonOrg = premiumMonOrg.equals("-1") ? "-" : premiumMonOrg;
				if(totCnt > -1 && basCnt == -1) //special case : when total monitor is given an Limited count, but basic monitor have -1 in licnese .
				{
					premiumMonOrg = "-";
					availCnt = "-";
				}
				exportDataObj.put("premMons_TotalCnt",premiumMonOrg);
				exportDataObj.put("premMons_UsedCnt",usedPrem+"@#@"+orgname+"@#@Premium Monitors");
				exportDataObj.put("premMons_AvailCnt",availCnt);
				csvRow += ","+premiumMonOrg+","+usedPrem+","+availCnt;

				//Network devices
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					usedCnt = used_network;
					used = String.valueOf(usedCnt);
				}
				else
				{
					detailsMap = certUsage.getNetworkDevicesDetailsForUser();
					used = (String)detailsMap.get("Used");
					usedCnt = Integer.parseInt(used);
				}
				int nwDevCnt = Integer.parseInt(networkDevOrg);
				availCnt = networkDevOrg.equals("-1") ? "-" : String.valueOf(nwDevCnt-usedCnt);
				networkDevOrg = networkDevOrg.equals("-1") ? "-" : networkDevOrg;
				exportDataObj.put("nwDev_TotalCnt",networkDevOrg);
				exportDataObj.put("nwDev_UsedCnt",used+"@#@"+orgname+"@#@Network device");
				exportDataObj.put("nwDev_AvailCnt",availCnt);
				csvRow += ","+networkDevOrg+","+used+","+availCnt;

				//User based (named or concurrent)
				if (isUserCertMgr)
				{
					used = "0";
					String peakCnt = "-", peakDate = "-";
					if (orgname.equalsIgnoreCase("egenterprise"))
					{
						int idx = mgr_used_userBasedCount.indexOf(".");
						if(idx > -1)
						{
							mgr_used_userBasedCount = mgr_used_userBasedCount.substring(0,idx);
						}
						used = mgr_used_userBasedCount;
						userBasedOrg =  mgr_allowed_userBasedCount;
						peakCnt = mgrPeakUsgCnt;
						peakDate = mgrPeakUsgDate;
					}
					else
					{
						//	used = (aListData != null && aListData.size() > 0) ? (String)aListData.get(0) : "0";
						//	used = (used.startsWith("0.")) ? used.substring(0,used.indexOf(".")) : "0";
						//	usedCnt = Integer.parseInt(used);
						//int usrBsdCnt = Integer.parseInt(userBasedOrg);
						userBasedOrg = userBasedOrg.equals("-1") ? "-" : userBasedOrg;

						//peakusage
						HashMap userMap = (userCertInfo != null) ? (HashMap)userCertInfo.get(orgname) : new HashMap();
						if (userMap != null)
						{
							Iterator it = userMap.keySet().iterator();
							while (it.hasNext())
							{
								String type = (String)it.next();
								String cnt = (String)userMap.get(type);
								if (type.equalsIgnoreCase("peakCount"))
								{
									peakCnt = cnt;
								}
								else if (type.equalsIgnoreCase("peakDate"))
								{
									peakDate = cnt;
								}
								else if(type.equalsIgnoreCase("Total"))
								{
									used = cnt;
								}
								int dotCnt = used.indexOf(".");
								if (dotCnt > -1)
								{
									used = used.substring(0,dotCnt);
								}
								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);
								}
							}
						}
					}
					exportDataObj.put("userBased_TotalCnt",userBasedOrg);
					exportDataObj.put("userBased_UsedCnt",used);
					exportDataObj.put("userBased_PeakCnt",peakCnt);
					exportDataObj.put("userBased_PeakDate",peakDate);
					csvRow += ","+userBasedOrg+","+used+","+peakCnt+",\""+peakDate+"\"";
				}

				//Monitor users
				if (orgname.equalsIgnoreCase("egenterprise"))
				{
					usedCnt = used_monUserCount;
					used = String.valueOf(usedCnt);
				}
				else 
				{
					used = "0";
					ArrayList usersUnderOU = uuidInfo.getAllSubOrgsAndUsers(orgname);
					if (usersUnderOU != null && usersUnderOU.size() > 0)
					{
						usersUnderOU.remove(orgname);
						used = String.valueOf(usersUnderOU.size());
					}
				}
				usedCnt = Integer.parseInt(used);
				int monUsrCnt = Integer.parseInt(userCntOrg);
				availCnt = userCntOrg.equals("-1") ? "-" : String.valueOf(monUsrCnt-usedCnt);
				userCntOrg = userCntOrg.equals("-1") ? "-" : userCntOrg;
				exportDataObj.put("userCnt_TotalCnt",userCntOrg);
				exportDataObj.put("userCnt_UsedCnt",used+"@#@"+orgname+"@#@Monitor users");
				exportDataObj.put("userCnt_AvailCnt",availCnt);
				csvRow += ","+userCntOrg+","+used+","+availCnt;
				csvData.add(csvRow);

				//for sub org datas (Organizational unit)
				JSONArray rootUserObjectArray = uuidInfo.buildOULicenseUsageTreeJson(orgname,false,aListData,userCertInfo,mgrLicDetails);
				if (!rootUserObjectArray.isEmpty())
				{
					exportDataObj.put("children",rootUserObjectArray);

					csvDataList = uuidInfo.getCsvDataForLicenseUsage();
					if (csvDataList != null)
					{
						for(int j=0; j<csvDataList.size(); j++)
						{
							List t1 = (List)csvDataList.get(j);
							String tempStr = t1.toString();
							tempStr = tempStr.substring(1,tempStr.length()-1);
							String[] strTkns = StringUtils.getTokens(tempStr,"#");
							for (int k=0; k<strTkns.length; k++)
							{
								String tStr = strTkns[k];
								if (tStr.startsWith(","))
								{
									tStr = tStr.substring(1);
									tStr = tStr.trim();
								}
								csvData.add(tStr);
							}
						}
						uuidInfo.clearCsvDataForLicenseUsage();
					}
				}

				exportDataArr.add(exportDataObj);
			}
			rootJson.put("exportDataArr",exportDataArr);
		}
		else //If it is 'enterprise' model, then the following block will be executed.
		{
			exportDataArr = new JSONArray();
			exportDataObj = new JSONObject();
			String orgname = "egenterprise";

			//for super org datas (Organization)
			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);

			//Getting license count values of user/organizational unit.
			String totMonOrg = String.valueOf(mgrAllowedTotalCnt);
			String basicMonOrg = String.valueOf(mgrAllowedBasicCnt);
			String premiumMonOrg = String.valueOf(mgrAllowedPremuCnt);
			String networkDevOrg = String.valueOf(mgrAllowedNwDevCnt);
			String userBasedOrg = String.valueOf(mgrAllowedUserCount);
			String userCntOrg = String.valueOf(mgrAllowedMonUserCount);

			//Getting used and available license count values of organizational unit/organization.
			csvRow = orgname;

			//Total monitors
			int totCnt = Integer.parseInt(totMonOrg);
			int usedCnt = used_total;
			String used = String.valueOf(usedCnt);
			String availCnt = totMonOrg.equals("-1") ? "-" : String.valueOf(totCnt-usedCnt);
			totMonOrg = totMonOrg.equals("-1") ? "-" : totMonOrg;
			exportDataObj.put("totMons_TotalCnt",totMonOrg);
			exportDataObj.put("totMons_UsedCnt",used+"@#@"+orgname+"@#@Total Monitors");
			exportDataObj.put("totMons_AvailCnt",availCnt);
			csvRow += ","+totMonOrg+","+used+","+availCnt;

			//Basic monitors
			usedCnt = used_basic;
			used = String.valueOf(usedCnt); 
			int basCnt = Integer.parseInt(basicMonOrg);
			int basicAvail = basCnt-usedCnt;
			if (basicAvail < 0)
			{
				basicAvail = 0;
			}
			availCnt = basicMonOrg.equals("-1") ? "-" : String.valueOf(basicAvail);
			basicMonOrg = basicMonOrg.equals("-1") ? "-" : basicMonOrg;
			exportDataObj.put("basMons_TotalCnt",basicMonOrg);
			exportDataObj.put("basMons_UsedCnt",used+"@#@"+orgname+"@#@Basic Monitors");
			exportDataObj.put("basMons_AvailCnt",availCnt);
			csvRow += ","+basicMonOrg+","+used+","+availCnt;

			//Premium monitors
			usedCnt = used_Premium;
			used = String.valueOf(usedCnt); 
			int premCnt = totCnt - basCnt;
			availCnt = premiumMonOrg.equals("-1") ? "-" : String.valueOf(premCnt-usedCnt);
			premiumMonOrg = premiumMonOrg.equals("-1") ? "-" : premiumMonOrg;
			if(totCnt > -1 && basCnt == -1) //special case : when total monitor is given an Limited count, but basic monitor have -1 in licnese .
			{
				premiumMonOrg = "-";
				availCnt = "-";
			}
			exportDataObj.put("premMons_TotalCnt",premiumMonOrg);
			exportDataObj.put("premMons_UsedCnt",used+"@#@"+orgname+"@#@Premium Monitors");
			exportDataObj.put("premMons_AvailCnt",availCnt);
			csvRow += ","+premiumMonOrg+","+used+","+availCnt;

			//Network devices
			usedCnt = used_network;
			used = String.valueOf(usedCnt);
			int nwDevCnt = Integer.parseInt(networkDevOrg);
			availCnt = networkDevOrg.equals("-1") ? "-" : String.valueOf(nwDevCnt-usedCnt);
			networkDevOrg = networkDevOrg.equals("-1") ? "-" : networkDevOrg;
			exportDataObj.put("nwDev_TotalCnt",networkDevOrg);
			exportDataObj.put("nwDev_UsedCnt",used+"@#@"+orgname+"@#@Network device");
			exportDataObj.put("nwDev_AvailCnt",availCnt);
			csvRow += ","+networkDevOrg+","+used+","+availCnt;

			//User based (named or concurrent)
			if (isUserCertMgr)
			{
				int idx = mgr_used_userBasedCount.indexOf(".");
				if(idx > -1)
				{
					mgr_used_userBasedCount = mgr_used_userBasedCount.substring(0,idx);
				}
				used = mgr_used_userBasedCount;
				userBasedOrg = mgr_allowed_userBasedCount;
				String peakCnt = mgrPeakUsgCnt;
				String peakDate = mgrPeakUsgDate;

				exportDataObj.put("userBased_TotalCnt",userBasedOrg);
				exportDataObj.put("userBased_UsedCnt",used);
				exportDataObj.put("userBased_PeakCnt",peakCnt);
				exportDataObj.put("userBased_PeakDate",peakDate);
				csvRow += ","+userBasedOrg+","+used+","+peakCnt+",\""+peakDate+"\"";
			}

			//Monitor users
			usedCnt = used_monUserCount;
			used = String.valueOf(usedCnt);
			int monUsrCnt = Integer.parseInt(userCntOrg);
			availCnt = userCntOrg.equals("-1") ? "-" : String.valueOf(monUsrCnt-usedCnt);
			userCntOrg = userCntOrg.equals("-1") ? "-" : userCntOrg;
			exportDataObj.put("userCnt_TotalCnt",userCntOrg);
			exportDataObj.put("userCnt_UsedCnt",used+"@#@"+orgname+"@#@Monitor users");
			exportDataObj.put("userCnt_AvailCnt",availCnt);
			csvRow += ","+userCntOrg+","+used+","+availCnt;
			csvData.add(csvRow);

			//for sub org datas (Organizational unit)
			JSONArray rootUserObjectArray = uuidInfo.buildOULicenseUsageTreeJson(orgname,false,aListData,userCertInfo,mgrLicDetails);
			if (!rootUserObjectArray.isEmpty())
			{
				exportDataObj.put("children",rootUserObjectArray);

				csvDataList = uuidInfo.getCsvDataForLicenseUsage();
				if (csvDataList != null)
				{
					for(int j=(csvDataList.size()-1); j>=0; j--)
					{
						List t1 = (List)csvDataList.get(j);
						String tempStr = t1.toString();
						tempStr = tempStr.substring(1,tempStr.length()-1);
						StringTokenizer strTkns = new StringTokenizer(tempStr,"#");
						while(strTkns.hasMoreTokens())
						{
							String tStr = strTkns.nextToken();
							if (tStr.startsWith(","))
							{
								tStr = tStr.substring(1);
								tStr = tStr.trim();
							}
							csvData.add(tStr);
						}
					}
					uuidInfo.clearCsvDataForLicenseUsage();
				}
			}

			exportDataArr.add(exportDataObj);
			rootJson.put("exportDataArr",exportDataArr);
		}
	}
	else //If logged in as limited admin access user, then following block will be executed.
	{
		exportDataArr = new JSONArray();
		exportDataObj = new JSONObject();

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

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

		//Getting license count values of user/organizational unit.
		String totMonOrg = String.valueOf(mgrAllowedTotalCnt);
		String basicMonOrg = String.valueOf(mgrAllowedBasicCnt);
		String premiumMonOrg = String.valueOf(mgrAllowedPremuCnt);
		String networkDevOrg = String.valueOf(mgrAllowedNwDevCnt);
		String userBasedOrg = String.valueOf(mgrAllowedUserCount);
		String userCntOrg = String.valueOf(mgrAllowedMonUserCount);
		ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,orgname);
		if (userAllowedLimits != null && userAllowedLimits.size() > 0)
		{
			totMonOrg = userAllowedLimits.get(0).toString();
			basicMonOrg = userAllowedLimits.get(1).toString();
			networkDevOrg = userAllowedLimits.get(2).toString();
			if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
			{
				userBasedOrg = userAllowedLimits.get(3).toString();
				userCntOrg = userAllowedLimits.get(4).toString();
			}
			else
			{
				userBasedOrg = "0";
				userCntOrg = userAllowedLimits.get(3).toString();
			}
			int allowedTotalCnt = Integer.parseInt(totMonOrg);
			int allowedBasicCnt = Integer.parseInt(basicMonOrg);
			int allowedPremuCnt = (allowedTotalCnt > -1 && allowedBasicCnt > -1) ? allowedTotalCnt - allowedBasicCnt : -1;
			premiumMonOrg = String.valueOf(allowedPremuCnt);
		}

		//Getting used and available license count values of organizational unit/organization.
		certUsage.setUserName(orgname);
		HashMap detailsMap = new HashMap();
		List orgNames = uuidInfo.getOrgNames(orgname);
		if (orgNames != null)
		{
			String reverseStr = "";
			for (int k=(orgNames.size()-1); k>=0; k--)
			{
				String str = (String)orgNames.get(k);
				reverseStr += str + "->";
			}
			if (reverseStr.length()>0)
			{
				reverseStr = (reverseStr.endsWith("->")) ? reverseStr.substring(0,reverseStr.length()-2) : reverseStr;
				csvRow = reverseStr;
			}
			else
			{
				csvRow = orgname;
			}
		}
		else
		{
			csvRow = orgname;
		}

		//Total monitors
		int totCnt = Integer.parseInt(totMonOrg);
		int usedCnt = 0;
		String used = "0";
		if (orgname.equalsIgnoreCase("egenterprise"))
		{
			usedCnt = used_total;
			used = String.valueOf(usedCnt);
		}
		else
		{
			detailsMap = certUsage.getTotalMonitorsDetailsForUser();
			used = (String)detailsMap.get("Used");
			usedCnt = Integer.parseInt(used);
		}
		String availCnt = totMonOrg.equals("-1") ? "-" : String.valueOf(totCnt-usedCnt);
		totMonOrg = totMonOrg.equals("-1") ? "-" : totMonOrg;
		exportDataObj.put("totMons_TotalCnt",totMonOrg);
		exportDataObj.put("totMons_UsedCnt",used+"@#@"+orgname+"@#@Total Monitors");
		exportDataObj.put("totMons_AvailCnt",availCnt);
		csvRow += ","+totMonOrg+","+used+","+availCnt;

		//Premium monitors and Basic monitors
		int usedPremium = 0, usedBasic = 0;
		String usedPrem = "0", usedBas = "0";
		if (orgname.equalsIgnoreCase("egenterprise"))
		{
			usedPremium = used_Premium;
			usedPrem = String.valueOf(usedPremium);
			usedBasic = used_basic;
			usedBas = String.valueOf(usedBasic);
		}
		else
		{
			detailsMap = certUsage.getPremiumMonitorsDetailsForUser();
			usedPrem = (String)detailsMap.get("Used");
			usedPremium = Integer.parseInt(usedPrem);
			detailsMap = certUsage.getBasicMonitorsDetailsForUser();
			usedBas = (String)detailsMap.get("Used");
			usedBasic = Integer.parseInt(usedBas);
		}
		//If basic comps exceeds the allowed count then it will consume premium license if exist.
		if (!basicMonOrg.equals("-1"))
		{
			int allowedBas = Integer.parseInt(basicMonOrg);
			if (usedBasic > allowedBas)
			{
				usedPremium += (usedBasic-allowedBas);
				usedBasic  = allowedBas;
				usedPrem = String.valueOf(usedPremium);
				usedBas = String.valueOf(usedBasic);
			}
		}
		int basCnt = Integer.parseInt(basicMonOrg);
		int basicAvail = basCnt-usedBasic;
		if (basicAvail < 0)
		{
			basicAvail = 0;
		}
		availCnt = basicMonOrg.equals("-1") ? "-" : String.valueOf(basicAvail);
		basicMonOrg = basicMonOrg.equals("-1") ? "-" : basicMonOrg;
		exportDataObj.put("basMons_TotalCnt",basicMonOrg);
		exportDataObj.put("basMons_UsedCnt",usedBas+"@#@"+orgname+"@#@Basic Monitors");
		exportDataObj.put("basMons_AvailCnt",availCnt);
		csvRow += ","+basicMonOrg+","+usedBas+","+availCnt;

		int premCnt = totCnt - basCnt;
		availCnt = premiumMonOrg.equals("-1") ? "-" : String.valueOf(premCnt-usedPremium);
		premiumMonOrg = premiumMonOrg.equals("-1") ? "-" : premiumMonOrg;
		if(totCnt > -1 && basCnt == -1) //special case : when total monitor is given an Limited count, but basic monitor have -1 in licnese .
		{
			premiumMonOrg = "-";
			availCnt = "-";
		}
		exportDataObj.put("premMons_TotalCnt",premiumMonOrg);
		exportDataObj.put("premMons_UsedCnt",usedPrem+"@#@"+orgname+"@#@Premium Monitors");
		exportDataObj.put("premMons_AvailCnt",availCnt);
		csvRow += ","+premiumMonOrg+","+usedPrem+","+availCnt;

		//Network devices
		if (orgname.equalsIgnoreCase("egenterprise"))
		{
			usedCnt = used_network;
			used = String.valueOf(usedCnt);
		}
		else
		{
			detailsMap = certUsage.getNetworkDevicesDetailsForUser();
			used = (String)detailsMap.get("Used");
			usedCnt = Integer.parseInt(used);
		}
		int nwDevCnt = Integer.parseInt(networkDevOrg);
		availCnt = networkDevOrg.equals("-1") ? "-" : String.valueOf(nwDevCnt-usedCnt);
		networkDevOrg = networkDevOrg.equals("-1") ? "-" : networkDevOrg;
		exportDataObj.put("nwDev_TotalCnt",networkDevOrg);
		exportDataObj.put("nwDev_UsedCnt",used+"@#@"+orgname+"@#@Network device");
		exportDataObj.put("nwDev_AvailCnt",availCnt);
		csvRow += ","+networkDevOrg+","+used+","+availCnt;

		//User based (named or concurrent)
		if (isUserCertMgr)
		{
			String peakCnt = "-", peakDate = "-";
			if (orgname.equalsIgnoreCase("egenterprise"))
			{
				used = mgr_used_userBasedCount;
				userBasedOrg =  mgr_allowed_userBasedCount;
				peakCnt = mgrPeakUsgCnt;
				peakDate = mgrPeakUsgDate;
			}
			else
			{
				//used = (aListData != null && aListData.size() > 0) ? (String)aListData.get(0) : "0";
				//used = (used.startsWith("0.")) ? used.substring(0,used.indexOf(".")) : "0";
				//usedCnt = Integer.parseInt(used);
				//int usrBsdCnt = Integer.parseInt(userBasedOrg);
				//availCnt = userBasedOrg.equals("-1") ? "-" : String.valueOf(usrBsdCnt-usedCnt);
				//userBasedOrg = userBasedOrg.equals("-1") ? "-" : userBasedOrg;

				//peakusage
				HashMap userMap = (userCertInfo != null) ? (HashMap)userCertInfo.get(orgname) : new HashMap();
				if (userMap != null)
				{
					Iterator it = userMap.keySet().iterator();
					while (it.hasNext())
					{
						String type = (String)it.next();
						String cnt = (String)userMap.get(type);
						if (type.equalsIgnoreCase("peakCount"))
						{
							peakCnt = cnt;
						}
						else if (type.equalsIgnoreCase("peakDate"))
						{
							peakDate = cnt;
						}
						else if(type.equalsIgnoreCase("Total"))
						{
							used = cnt;
						}
						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);
						}
					}
				}
			}
			int idxDec = used.indexOf(".");
			if (idxDec > -1)
			{
				used = used.substring(0,idxDec);
			}
			exportDataObj.put("userBased_TotalCnt",userBasedOrg);
			exportDataObj.put("userBased_UsedCnt",used);
			exportDataObj.put("userBased_PeakCnt",peakCnt);
			exportDataObj.put("userBased_PeakDate",peakDate);
			csvRow += ","+userBasedOrg+","+used+","+peakCnt+",\""+peakDate+"\"";
		}

		//Monitor users
		if (orgname.equalsIgnoreCase("egenterprise"))
		{
			usedCnt = used_monUserCount;
			used = String.valueOf(usedCnt);
		}
		else
		{
			used = "0";
			ArrayList usersUnderOU = uuidInfo.getAllSubOrgsAndUsers(orgname);
			if (usersUnderOU != null && usersUnderOU.size() > 0)
			{
				usersUnderOU.remove(orgname);
				used = String.valueOf(usersUnderOU.size());
			}
		}
		usedCnt = Integer.parseInt(used);
		int monUsrCnt = Integer.parseInt(userCntOrg);
		availCnt = userCntOrg.equals("-1") ? "-" : String.valueOf(monUsrCnt-usedCnt);
		userCntOrg = userCntOrg.equals("-1") ? "-" : userCntOrg;
		exportDataObj.put("userCnt_TotalCnt",userCntOrg);
		exportDataObj.put("userCnt_UsedCnt",used+"@#@"+orgname+"@#@Monitor users");
		exportDataObj.put("userCnt_AvailCnt",availCnt);
		csvRow += ","+userCntOrg+","+used+","+availCnt;
		csvData.add(csvRow);

		//for sub org datas (Organizational unit)
		JSONArray rootUserObjectArray = uuidInfo.buildOULicenseUsageTreeJson(orgname,false,aListData,userCertInfo,mgrLicDetails);
		if (!rootUserObjectArray.isEmpty())
		{
			exportDataObj.put("children",rootUserObjectArray);

			csvDataList = uuidInfo.getCsvDataForLicenseUsage();
			if (csvDataList != null)
			{
				for(int j=(csvDataList.size()-1); j>=0; j--)
				{
					List t1 = (List)csvDataList.get(j);
					String tempStr = t1.toString();
					tempStr = tempStr.substring(1,tempStr.length()-1);
					StringTokenizer strTkns = new StringTokenizer(tempStr,"#");
					while(strTkns.hasMoreTokens())
					{
						String tStr = strTkns.nextToken();
						if (tStr.startsWith(","))
						{
							tStr = tStr.substring(1);
							tStr = tStr.trim();
						}
						csvData.add(tStr);
					}
				}
				uuidInfo.clearCsvDataForLicenseUsage();
			}
		}

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

	if (exportDataArr.isEmpty())
	{
		rootJson.put("isUsersCreated",new Boolean(false));
		out.println(rootJson);
		return;
	}

	rootJson.put("isMgrConcUserBased",isCCUserCertEnabled);
	rootJson.put("isMgrNamedUserBased",isNamedUserEnabled);

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

	
%>

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



