<%@ page import = "egurkha.UserBean"%>
<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.*"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.eg.EgConMonHelper"%>
<%@ page import = "java.sql.*"%>
<%@ page import="com.egurkha.util.StringUtils"%>
<%!

	private long getTotalNoOfUsers()
	{
		ArrayList userTestNames = getUserTests();
		String iniFileDir = EgInstallInfo.getInstallDir()+ "/manager/config/";
		long totalNoOfUsers = 0;
		boolean isVM = false;
		int computeDuration = 90;
		IniFile dbaseIni = new IniFile(iniFileDir+"eg_dbase.ini");

		for (int u=0;u < userTestNames.size() ;u++)
		{
			String testName  = userTestNames.get(u).toString();
			String strVal = dbaseIni.getValue("DYN_TABLES",testName);
			//if (strVal != null && (strVal.equalsIgnoreCase("yes") || strVal.equalsIgnoreCase("true")) )
			{
				if (testName.equalsIgnoreCase("EsxGuestTest"))
				{
					isVM  =true;
				}
				totalNoOfUsers += getUserCount(testName,isVM,computeDuration);
			}
		}
		//System.out.println("Total No of named users :"+totalNoOfUsers);
		return totalNoOfUsers;
	}

	private boolean isOracleDB()
	{
		String iniFileDir = EgInstallInfo.getInstallDir()+ "/manager/config/";
		IniFile iniDB = new IniFile(iniFileDir+"eg_db.ini");
		String dbType = iniDB.getValue("DB_PROPERTIES","DB_Server_Type");
		if (dbType != null && dbType.equalsIgnoreCase("EgOracleAdapter"))
		{
			return true;
		}else
		{
			return false;
		}
	}

	private ArrayList getUserTests()
	{
		ArrayList userTestNames = new ArrayList();
		userTestNames.add("TermUserTest");
		userTestNames.add("CtxXpUserTest");
		userTestNames.add("EsxGuestTest");
		userTestNames.add("HvGuestTest");
		userTestNames.add("RHEVGuestTest");
		userTestNames.add("VmGuestTest");
		userTestNames.add("XenGuestTest");
		userTestNames.add("OraVBoxGuestTest");
		return userTestNames;
	}

	private int getUserCount(String strTest,boolean isVm,int computeDuration)
	{
		int strReurtun = 0;
		Vector vecUser = new Vector();
		EgDbAdapterUI adapter = EgDbAdapterTypeUI.getObject();
		try{
			adapter.setConnection();
			String strQuery = "";
			if (isOracleDB())
			{
				//strQuery  = buildOracleQueryforUserDetails(strTest,"info",isVm,computeDuration,false);
				strQuery  = buildOracleQueryforUserDetails(strTest,"info",isVm,computeDuration,true);
			}
			else
			{
				//strQuery  = buildSQLQueryforUserDetails(strTest,"info",isVm,computeDuration,false);
				strQuery  = buildSQLQueryforUserDetails(strTest,"info",isVm,computeDuration,true);
			}
			//System.out.println("query :"+strQuery);
			//buildQueryforUserDetails(strTest,"info",isVm,computeDuration,false);

			ResultSet rs = adapter.dbselect(strQuery);
			//ResultSet rs = null;
			if (rs!=null)
			{
				while(rs.next())
				{
					String strUser = rs.getString(1);
					if(isVm)
					{
						if(strUser!=null && strUser.indexOf("_on_")>-1 )
							strUser = strUser.substring(0,strUser.indexOf("_on_"));
						else
							strUser = null;
					}
					if(strUser!=null && !vecUser.contains(strUser))
						vecUser.add(strUser);
				}
			}
			if(rs!=null)
				rs.close();
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			adapter.release_Connection(true);
			EgDbAdapterTypeUI.releaseObject(adapter);
		}
		if(vecUser!=null && vecUser.size()>0)
			strReurtun = vecUser.size();

		return strReurtun;
	}

	private String buildOracleQueryforUserDetails(String strTest,String strUserNameCol,boolean isVm,int duration,boolean needIncludeCurrentTime)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("Select DISTINCT("+strUserNameCol+") from "+strTest);
		if(isVm)
			sb.append(" WHERE info like '%_on_%'");
		if(duration!=-1)
		{
			egurkha.reporter.ErEsxVMutils ervm = new egurkha.reporter.ErEsxVMutils();
			HashMap mapTimeLine = ervm.getDateTime(duration+" days","Yes");

 			String startDate = (String)mapTimeLine.get("dbstartdate");
			String endDate = (String)mapTimeLine.get("dbenddate");
			String strStartTime = startDate;
			String strEndTime = endDate;
			if(needIncludeCurrentTime)
			{
				String s_st_hr = (String)mapTimeLine.get("startHour");
				String s_en_hr = (String)mapTimeLine.get("endHour");
				String strmin = (String)mapTimeLine.get("startMin");
				String enmin = (String)mapTimeLine.get("endMin");
				strStartTime +=" "+s_st_hr+":"+strmin+":00";
				strEndTime +=" "+s_en_hr+":"+enmin+":00";
			}else
			{
				strStartTime +=" 00:00:00";
				strEndTime +=" 00:00:00";
			}
			if(isVm)
				sb.append(" AND ");
			else
				sb.append(" WHERE ");
			sb.append(" MSMT_TIME >=  TO_DATE('" + strStartTime + "','dd/mm/yyyy hh24:mi:ss') AND MSMT_TIME <  TO_DATE('"+ strEndTime + "','dd/mm/yyyy hh24:mi:ss') ");
		}
		return sb.toString();
	}

	private String buildSQLQueryforUserDetails(String strTest,String strUserNameCol,boolean isVm,int duration,boolean needIncludeCurrentTime)
	{
		StringBuffer sb = new StringBuffer();
		sb.append("Select DISTINCT("+strUserNameCol+") from "+strTest);
		if(isVm)
			sb.append(" WHERE info like '%_on_%'");
		if(duration!=-1)
		{
			egurkha.reporter.ErEsxVMutils ervm = new egurkha.reporter.ErEsxVMutils();
			HashMap mapTimeLine = ervm.getDateTime(duration+" days","Yes");

			String startDate = (String)mapTimeLine.get("dbstartdate");
			String endDate = (String)mapTimeLine.get("dbenddate");
			String strStartTime = startDate;
			String strEndTime = endDate;
			if(needIncludeCurrentTime)
			{
				String s_st_hr = (String)mapTimeLine.get("startHour");
				String s_en_hr = (String)mapTimeLine.get("endHour");
				String strmin = (String)mapTimeLine.get("startMin");
				String enmin = (String)mapTimeLine.get("endMin");
				strStartTime +=" "+s_st_hr+":"+strmin+":00";
				strEndTime +=" "+s_en_hr+":"+enmin+":00";
			}else
			{
				strStartTime +=" 00:00:00";
				strEndTime +=" 00:00:00";
			}
			if(isVm)
				sb.append(" AND ");
			else
				sb.append(" WHERE ");

			sb.append(" msmt_time >= "
						+ " CONVERT(datetime,'" + strStartTime + "',103) AND "
								+ " msmt_time < CONVERT(datetime,'"+ strEndTime + "',103) ");
		}
		return sb.toString();
		
	}

	private ArrayList nicksAlone(List servers)
	{
		ArrayList result = new ArrayList();
		if (servers != null)
		{
			for (int s=0;s < servers.size();s++)
			{
				String tmp = servers.get(s).toString();
				tmp = tmp.substring(tmp.indexOf(":")+1);
				tmp = tmp.substring(0,tmp.indexOf(":"));
				result.add(tmp);
			}
		}
		return result;
	}

	private int getMonitorCountForServers(ArrayList serverList)
	{
		EgDiscInfo discInfo = new EgDiscInfo("manager");
		ArrayList totalApps =  discInfo.getAllApps();
		ArrayList totalAppsNicks = new ArrayList();
		if (totalApps != null)
		{
			totalAppsNicks = nicksAlone(totalApps);
		}
		ArrayList totalList = new ArrayList();
		
		for (int s=0;s < serverList.size() ;s++ )
		{
			String serverType = serverList.get(s).toString();
			String [] comps  = discInfo.getAllServersOfType(serverType);
			ArrayList compsNicks = new ArrayList();
			if (comps != null)
			{
				compsNicks = nicksAlone(Arrays.asList(comps));
			}

			for (int x=0;x < compsNicks.size() ;x++ )
			{
				String nick = compsNicks.get(x).toString();
				if (totalAppsNicks.contains(nick))// && !totalList.contains(nick))
				{
					totalList.add(nick);
				}
			}
		}
		return totalList.size();
	}
%>

<%
	String comeFrom = request.getParameter("comeFrom");
	if (!StringUtils.isNull(comeFrom) && comeFrom.equals("VDI"))
	{
		session.setAttribute("treeViewSrc","vdiuc");
	}
	String tool = "vdiuc";
	String sessionInUse = request.getParameter("sessionInUse");
	String pwd = request.getParameter("pwd");
	String authenticated = (String)session.getAttribute("authenticated");

	if (authenticated == null)
	{
		// Direct access from the browser address bar or from inside the toolkit via the tool
		if (pwd == null)
		{
			if (sessionInUse == null)
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom="+tool+"&tools="+tool);
			}
			else
			{
%>
				<script type="text/javascript">
					window.parent.location.href="/final/toolkitlogin";
				</script>
<%
			}
		}
		else
		{
			// Direct access from the browser address bar
			if (!pwd.equals(EgConMonHelper.executePwd))
			{
				response.sendRedirect(request.getContextPath()+"/toolkitlogin?comeFrom="+tool+"&tools="+tool);
			}
			else
			{
				session.setAttribute("reqFromForTk","vdiuc");
				session.setAttribute("validate_tools","true");
				session.setAttribute("tools",tool);
				String redirectURL = request.getContextPath()+"/toolkit";
				response.sendRedirect(redirectURL);
			}
		}
	}
	else
	{ 
		// Direct access from the browser address bar and session in use
		if (sessionInUse == null)
		{
			session.setAttribute("validate_tools","true");
			session.setAttribute("tools",tool);
			response.sendRedirect(request.getContextPath()+"/toolkit");
		}
	}

	session.setAttribute("reqFromForTk","vdiuc");
	long totalUsers = getTotalNoOfUsers();
%>
<html>
<head>
<link rel="stylesheet" href="eg_styles/eg_adminstyle.css" />
<script language="javascript" src="/final/admin/eg_scripts/timeout.js"></script>
<head>
<body>
<br><br>
<table border="1" width="55%" align="center">
	<tr>
		<td align ="left" width="45%" class="errortext" id="subhead" nowrap ><b>Name</b></td>
		<td align ="left" width="10%" class="errortext" id="subhead" nowrap ><b>Value</b></td>
	</tr>
	<tr>
		<td>Total number of named users</td>
		<td>
<%
		out.println(totalUsers);
%>
		</td>
	</tr>
<%
		ArrayList ctxAndTerminal = new ArrayList();
		ctxAndTerminal.add("Citrix_server");
		ctxAndTerminal.add("Terminal_server");
		int xenAndTermcount = getMonitorCountForServers(ctxAndTerminal);
%>
	<tr>
		<td>Total number of XenApp/Terminal servers monitored</td>
		<td>
<%
		out.println(xenAndTermcount);
%>
		</td>
	</tr>
<%
		ArrayList vdiTypes = new ArrayList();
		vdiTypes.add("Vmware_vdi_server");
		vdiTypes.add("VmVdi_i_server");
		vdiTypes.add("HyperV_VDI_server");
		vdiTypes.add("Xen_desktop_server");
		vdiTypes.add("Redhat_linux_vdi");
		vdiTypes.add("Oracle_vdi_VirtualBox");

		int vdiCompsCount = getMonitorCountForServers(vdiTypes);
%>
	<tr>
		<td>Total number of VDI servers monitored</td>
		<td>
<%
		out.println(vdiCompsCount);
%>
		</td>
	</tr>
<%
		UserBean userBean = new UserBean();
		int basicMonitorsCount = userBean.getBasicMonitorsCount();
		int premiumMonitorsCount = userBean.getPremiumMonitorsCount();
		int totalNoOfMonitors = basicMonitorsCount + premiumMonitorsCount;
%>
	<tr>
		<td>Total number of monitors being currently used</td>
		<td>
<%
		out.println(totalNoOfMonitors);
%>
		</td>
	</tr>
<table>
</body>
</html>



