<%
/*******************************************************************************
*	Name            :       UserLicenseJSONp.jsp
*	Purpose         :       To Add/Modify/Delete 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.egurkha.util.StringUtils" %>
<%@ page import = "com.eg.EgCrypt" %>
<%@ page import = "com.eg.EgCertUsage" %>
<%@ page import = "com.eg.EgUsersInfo" %>
<%@ page import = "com.eg.CertValidator" %>
<%@ page import = "com.eg.GroupCertValidator" %>
<%@ page import="net.sf.json.*"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>

<%
	JSONObject rootJson = new JSONObject();

	AuditLogThread auditLogThread = new AuditLogThread();
	auditLogThread.setValue("Category","Admin");
	auditLogThread.setValue("User_id",_user.getLoginID());
	auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
	auditLogThread.setValue("Session_id",session.getId());
	auditLogThread.setValue("Module","User License Management");
	auditLogThread.setValue("Activity","User License");

	String from = request.getParameter("from");
	String userName = request.getParameter("userName");
	String totalMonitors = request.getParameter("totalMonitors");
	String basicMonitors = request.getParameter("basicMonitors");
	String networkDevices = request.getParameter("networkDevices");
	String userBased = request.getParameter("userBased");
	String usersTotCount = request.getParameter("usersTotCount");
	String userLicSpecific = request.getParameter("userLicSpecific");
	String action = request.getParameter("action");
	String resetAllToDefault = request.getParameter("resetAllToDefault");

	boolean isMgrConcUserBased = EgInstallInfo.isconcurrentUserLicense;
	boolean isMgrNamedUserBased = EgInstallInfo.isnamedUserLicense;

	String value = "";
	String isMgrUsedBased = "false";

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

	EgUuidInfo uuidInfo = new EgUuidInfo();
	IniFile userCompMapIni = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir()+"/manager/config/eg_usercompmapping.ini");
	String[] userNames = userCompMapIni.getVariables("Users_Allowed_Count");
	ArrayList availUsersList = new ArrayList(Arrays.asList(userNames));

	//getting total license count of manager
	CertValidator cert = new CertValidator();
	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"))
	{
		long mgrConcUserCount = EgInstallInfo.allowedConcUsers;
		long mgrNamedUserCount = EgInstallInfo.allowedNamedUsers;
		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 = -1;
		}
		else
		{
			userBasedCount = Integer.parseInt(AllowedCount);
		}
	}
	
	/*
	 * for enterprise/MSP model - modify and delete action
	 */
	if (from != null && from.equalsIgnoreCase("userWiseView"))
	{
		IniFile egMgrMisc = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_mgrmisc.ini");
		//Vector defaultLicenseVar  = egMgrMisc.getAllValues("DEFAULT_LICENSING_POLICY");
		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);
		}
		//Action for 'single row modify/set to default' icon
		if(action !=null && userName != null && userLicSpecific != null && userLicSpecific.equalsIgnoreCase("yes"))
		{
			if (action.equalsIgnoreCase("modify"))
			{
				if(totalMonitors != null || totalMonitors != "")
				{
					totalMonitors = (totalMonitors.equalsIgnoreCase("unlimited")) ? "-1" : totalMonitors;
					value = totalMonitors + "#";
				}
				if(basicMonitors != null || basicMonitors != "")
				{
					basicMonitors = (totalMonitors.equals("-1") || basicMonitors.equalsIgnoreCase("unlimited")) ? "-1" : basicMonitors;
					value += basicMonitors + "#";
				}
				if(networkDevices != null || networkDevices != "")
				{
					networkDevices = (networkDevices.equalsIgnoreCase("unlimited")) ? "-1" : networkDevices;
					value += networkDevices;
				}
				if (isMgrUsedBased.equalsIgnoreCase("true") && (userBased != null || userBased != ""))
				{
					userBased = (userBased.equalsIgnoreCase("unlimited")) ? "-1" : userBased;
					value +=  "#" + userBased;
				}
				else
				{
					userBased = "0";
					value +=  "#" + userBased;
				}
				if(usersTotCount != null || usersTotCount != "")
				{
					usersTotCount = (usersTotCount.equalsIgnoreCase("unlimited")) ? "-1" : usersTotCount;
					value += "#" + usersTotCount;
				}
				value = EgCrypt.AESencrypt(value);

				/* Audit log code - starts */
				String totMonSpecific = String.valueOf(totalMonitorsCount);
				String basicMonSpecific = String.valueOf(basicMonitorsCount);
				String networkDevSpecific = String.valueOf(networkMonitorsCount);
				String userBasedSpecific = String.valueOf(userBasedCount);
				String userCountSpecific = String.valueOf(monitorUsersCount);
				ArrayList userAllowedLimits = getValidLicenseCount(availUsersList,userCompMapIni,uuidInfo,userName);
				if (userAllowedLimits != null && userAllowedLimits.size() > 0)
				{
					totMonSpecific = userAllowedLimits.get(0).toString();
					basicMonSpecific = userAllowedLimits.get(1).toString();
					networkDevSpecific = userAllowedLimits.get(2).toString();
					if (isMgrUsedBased.equalsIgnoreCase("true") || userAllowedLimits.size()==5)
					{
						userBasedSpecific = userAllowedLimits.get(3).toString();
						userCountSpecific = userAllowedLimits.get(4).toString();
					}
					else
					{
						userBasedSpecific = "0";
						userCountSpecific = userAllowedLimits.get(3).toString();
					}
				}
				
				auditLogThread.setPreviousValue("01~~Total Monitors",checkUnlimitCount(totMonSpecific));
				auditLogThread.setPreviousValue("02~~Basic Monitors",checkUnlimitCount(basicMonSpecific));
				auditLogThread.setPreviousValue("03~~Network Devices",checkUnlimitCount(networkDevSpecific));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setPreviousValue("04~~Concurrent Users",checkUnlimitCount(userBasedSpecific));
					}
					else if(isMgrNamedUserBased)
					{
						auditLogThread.setPreviousValue("04~~Named Users",checkUnlimitCount(userBasedSpecific));
					}
				}
				auditLogThread.setPreviousValue("05~~Users Count",checkUnlimitCount(userCountSpecific));
				/* Audit log code - ends */

				//setting current value 
				if (value != null && !value.equals(""))
				{
					userCompMapIni.setValue("Users_Allowed_Count",userName,value);
					userCompMapIni.saveFile();
				}

				/* Audit log code - starts */
				auditLogThread.setValue("Description","User License for the user "+userName+" has been updated");
				auditLogThread.setCurrentValue("01~~Total Monitors",checkUnlimitCount(totalMonitors));
				auditLogThread.setCurrentValue("02~~Basic Monitors",checkUnlimitCount(basicMonitors));
				auditLogThread.setCurrentValue("03~~Network Devices",checkUnlimitCount(networkDevices));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setCurrentValue("04~~Concurrent Users",checkUnlimitCount(userBased));
					}
					else if(isMgrNamedUserBased)
					{
						auditLogThread.setCurrentValue("04~~Named Users",checkUnlimitCount(userBased));
					}
				}
				auditLogThread.setCurrentValue("05~~Users Count",checkUnlimitCount(usersTotCount));
				auditLogThread.sendItToDB();
				/* Audit log code - ends */
			}
			if (action.equalsIgnoreCase("setDefault"))
			{
				String tot_mon = "";
				String bas_mon = "";
				String net_dev = "";
				String user_bas = "";
				String user_cnt = "";
				String userValue = userCompMapIni.getValue("Users_Allowed_Count",userName);
				String tempVal = EgCrypt.AESdecrypt(userValue);
				StringTokenizer stTknzr = new StringTokenizer(tempVal,"#");
				int tknsCnt = stTknzr.countTokens();
				if(tknsCnt >= 4)
				{
					tot_mon = stTknzr.nextToken();
					bas_mon = stTknzr.nextToken();
					net_dev = stTknzr.nextToken();
					if(tknsCnt == 5)
					{
						user_bas = stTknzr.nextToken();
					}
					user_cnt = stTknzr.nextToken();
				}

				/* Audit log code - starts */
				auditLogThread.setValue("Description","User License for the user "+userName+" have been updated successfully");
				auditLogThread.setPreviousValue("01~~Total Monitors",checkUnlimitCount(tot_mon));
				auditLogThread.setPreviousValue("02~~Basic Monitors",checkUnlimitCount(bas_mon));
				auditLogThread.setPreviousValue("03~~Network Devices",checkUnlimitCount(net_dev));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setPreviousValue("04~~Concurrent Users",checkUnlimitCount(user_bas));
					}
					else if(isMgrNamedUserBased)
					{
						auditLogThread.setPreviousValue("04~~Named Users",checkUnlimitCount(user_bas));
					}
				}
				auditLogThread.setPreviousValue("05~~Users Count",checkUnlimitCount(user_cnt));
				
				/*Iterator itt = defaultLicenseVar.iterator();
				while(itt.hasNext())
				{
					value+= (String) itt.next()+"#";
				}*/
				if (defaultValue != null && !defaultValue.equals(""))
				{
					//value = value.substring(0,value.length()-1);
					defaultValue = EgCrypt.AESencrypt(defaultValue);
				}
				userCompMapIni.setValue("Users_Allowed_Count",userName,defaultValue);
				//deleting current user value
				//userCompMapIni.deleteValue("Users_Allowed_Count",userName);
				userCompMapIni.saveFile();
				
				tot_mon = String.valueOf(totalMonitorsCount);
				bas_mon = String.valueOf(basicMonitorsCount);
				net_dev = String.valueOf(networkMonitorsCount);
				user_bas = String.valueOf(userBasedCount);
				user_cnt = String.valueOf(monitorUsersCount);

				auditLogThread.setCurrentValue("01~~Total Monitors",checkUnlimitCount(tot_mon));
				auditLogThread.setCurrentValue("02~~Basic Monitors",checkUnlimitCount(bas_mon));
				auditLogThread.setCurrentValue("03~~Network Devices",checkUnlimitCount(net_dev));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setCurrentValue("04~~Concurrent Users",checkUnlimitCount(user_bas));
					}
					else
					{
						auditLogThread.setCurrentValue("04~~Named Users",checkUnlimitCount(user_bas));
					}
				}
				auditLogThread.setCurrentValue("05~~Users Count",checkUnlimitCount(user_cnt));
				auditLogThread.sendItToDB();
				/* Audit log code - ends */
			}
		}
		
		//Action for 'delete all' button
		if (resetAllToDefault != null && (resetAllToDefault.equalsIgnoreCase("true") || resetAllToDefault.equalsIgnoreCase("yes")))
		{
			EgUserRole usrRole = _user.getUserRole();
			boolean hasAllComponentAccess = usrRole.hasAllComponentAccess();
			Vector orgSpecificUserList = new Vector();
			if (!hasAllComponentAccess)
			{
				String orgname = "";
				String session_userid = _user.getLoginID();
				boolean isSuperOrg = uuidInfo.isSuperOrg(session_userid);
				boolean isOrg = uuidInfo.isOrg(session_userid);
				if (isSuperOrg || isOrg)
				{
					orgname = session_userid;
				}
				else
				{
					orgname = uuidInfo.getDirectDependentOU(session_userid);
				}

				orgSpecificUserList.addAll(uuidInfo.getAllUsersUnderOrg(orgname));
				orgSpecificUserList.add(orgname);
			}

			String[] userNameVars = userCompMapIni.getVariables("Users_Allowed_Count");
			int userNameSize = userNameVars.length;

			Vector existingUsers = new Vector();
			String tmpVal = "";
			String tot_monitors = "";
			String bas_monitors = "";
			String net_devices = "";
			String user_based = "";
			String user_count = "";
			/*Iterator itt = defaultLicenseVar.iterator();
			while(itt.hasNext())
			{
				value+= (String) itt.next()+"#";
			}*/
			if (defaultValue != null && !defaultValue.equals(""))
			{
				//defaultValue = defaultValue.substring(0,defaultValue.length()-1);
				defaultValue = EgCrypt.AESencrypt(defaultValue);
			}
			for(int j=0; j<userNameSize; j++)
			{
				if (!hasAllComponentAccess && !orgSpecificUserList.contains(userNameVars[j]))
				{
					continue;
				}

				existingUsers.add(userNameVars[j]);
				String userVal = userCompMapIni.getValue("Users_Allowed_Count",userNameVars[j]);
				tmpVal = EgCrypt.AESdecrypt(userVal);
				StringTokenizer sttTknzr = new StringTokenizer(tmpVal,"#");
				int tknsCount = sttTknzr.countTokens();
				if(tknsCount >= 4)
				{
					tot_monitors = sttTknzr.nextToken();
					bas_monitors = sttTknzr.nextToken();
					net_devices = sttTknzr.nextToken();
					if(tknsCount == 5)
					{
						user_based = sttTknzr.nextToken();
					}
				}
				user_count = sttTknzr.nextToken();

				/* Audit log code - starts */
				auditLogThread = new AuditLogThread();
				auditLogThread.setValue("Category","Admin");
				auditLogThread.setValue("User_id",_user.getLoginID());
				auditLogThread.setValue("Host_ip",_user.getUserIP(session.getId()));
				auditLogThread.setValue("Session_id",session.getId());
				auditLogThread.setValue("Module","User License Management");
				auditLogThread.setValue("Activity","User License");
				auditLogThread.setValue("Description","User License for the user "+userNameVars[j]+" have been updated successfully");
				auditLogThread.setPreviousValue("01~~Total Monitors",checkUnlimitCount(tot_monitors));
				auditLogThread.setPreviousValue("02~~Basic Monitors",checkUnlimitCount(bas_monitors));
				auditLogThread.setPreviousValue("03~~Network Devices",checkUnlimitCount(net_devices));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setPreviousValue("04~~Concurrent Users",checkUnlimitCount(user_based));
					}
					else if(isMgrNamedUserBased)
					{
						auditLogThread.setPreviousValue("04~~Named Users",checkUnlimitCount(user_based));
					}
				}
				auditLogThread.setPreviousValue("05~~Users Count",checkUnlimitCount(user_count));

				tot_monitors = String.valueOf(totalMonitorsCount);
				bas_monitors = String.valueOf(basicMonitorsCount);
				net_devices = String.valueOf(networkMonitorsCount);
				user_based = String.valueOf(userBasedCount);
				user_count = String.valueOf(monitorUsersCount);
				auditLogThread.setCurrentValue("01~~Total Monitors",checkUnlimitCount(tot_monitors));
				auditLogThread.setCurrentValue("02~~Basic Monitors",checkUnlimitCount(bas_monitors));
				auditLogThread.setCurrentValue("03~~Network Devices",checkUnlimitCount(net_devices));
				if (isMgrUsedBased.equalsIgnoreCase("true"))
				{
					if(isMgrConcUserBased)
					{
						auditLogThread.setCurrentValue("04~~Concurrent Users",checkUnlimitCount(user_based));
					}
					else
					{
						auditLogThread.setCurrentValue("04~~Named Users",checkUnlimitCount(user_based));
					}
				}
				auditLogThread.setCurrentValue("05~~Users Count",checkUnlimitCount(user_count));
				auditLogThread.sendItToDB();
				/* Audit log code - ends */
				userCompMapIni.setValue("Users_Allowed_Count",userNameVars[j],defaultValue);
			}
		//	if (existingUsers != null && existingUsers.size() > 0)
		//	{
		//		userCompMapIni.deleteValues("Users_Allowed_Count",existingUsers);
		//		userCompMapIni.saveFile();
		//	}
			userCompMapIni.saveFile();
		}
	}
	EgConfigFilesSync.releaseInstance(userCompMapIni);
	rootJson.put("updateUrl","EgUserLicense.jsp");
	rootJson.put("success","true");
	out.println(rootJson.toString());
%>

<%!
	private String checkUnlimitCount(String count)
	{
		if (count != null && count.equals("-1"))
		{
			return "Unlimited";
		}
		return count;
	}

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


