<%@ include file="../../EgTrackerAJSON.jsp"%>
<%@ page import="com.egurkha.util.*" %>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "com.eg.geoLocationInformation"%>
<%@ page import = "java.util.*"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import ="java.text.SimpleDateFormat"%>
<%@ page import = "net.sf.json.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>

<%!
	public String removeChar(String source,char rem)
	{
		int i=0;
		while(true)
		{
			i=source.indexOf(".",0);
			if(i==-1) break;
			source=source.substring(0,i)+source.substring(i+1,source.length());
		}
		return source;
	}

	boolean isValidIPAddress(String ipAddress)
	{
		String a[] = StringUtils.getTokens(ipAddress,".");
		if(a==null || a.length!=4)
			return false;
		for(int i=0;i<a.length;i++)
		{
			try
			{
				if(Integer.parseInt(a[i]) > 255 || Integer.parseInt(a[i]) < 0 )
					return false;
			}
			catch(Exception e)
			{
				return false;
			}
		}
		return true;
	}
%>

<%
	JSONArray tmpArray = new JSONArray();
	JSONObject rootObj = new JSONObject();
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
	response.setContentType("application/json");
	String refreshButtonwidth="";
	
	if(trackerLanguage!=null && (trackerLanguage.equals("en_US") || trackerLanguage.equals("ch_CH") || trackerLanguage.equals("ja_JP") || trackerLanguage.equals("ko_KR") || trackerLanguage.equals("th_TH")))
	{
		refreshButtonwidth="width: 70px;";
	}
	else if(trackerLanguage!=null && (trackerLanguage.equals("fr_FR") || trackerLanguage.equals("de_DE") || trackerLanguage.equals("es_ES") || trackerLanguage.equals("it_IT") || trackerLanguage.equals("pt_BR")))
	{
		refreshButtonwidth="width:95px;";
	}

	UserRegistry userRregistry = UserRegistry.getInstance();
	Map sessGrpUser = userRregistry.getLoggedInGroupUsers();
	Map sess_info = userRregistry.getSessionMappings();

	Map tmp_sess_info = new HashMap();
	tmp_sess_info.putAll(sess_info);

	EgUserRole userRole = _user.getUserRole();
	boolean hasAllComponentAccess = userRole.hasAllComponentAccess();
	
	Map tmp_sess_info1 = new HashMap();
	Vector orgSpecificUserList = new Vector();

	IniFile ServicesIni = new IniFile(EgInstallInfo.getInstallDir()+"/manager/config/eg_services.ini");
	String eGMgrModel = ServicesIni.getValue("MISC_ARGS","eGMgrModel");
	
	User user = registry.getUser(session.getId());
	String unamestr = user.getLoginID();

	EgUuidInfo egUuidInfo = new EgUuidInfo();

	if(!hasAllComponentAccess)
	{
		String sess_userid = (String)session.getAttribute("sess_userid");
		String orgname = "";
		boolean isSuperOrg = egUuidInfo.isSuperOrg(sess_userid);
		boolean isOrg = egUuidInfo.isOrg(sess_userid);
		if (isSuperOrg)
		{
			orgname = sess_userid;
			orgSpecificUserList.add(orgname);
		}
		else if (isOrg)
		{
			orgname = sess_userid;
			orgSpecificUserList.add(orgname);
		}
		else
		{
			orgname = egUuidInfo.getDirectDependentOU(sess_userid);
		}
		orgSpecificUserList.addAll(egUuidInfo.getAllUsersUnderOrg(orgname));
		Iterator sess_it1= tmp_sess_info.keySet().iterator();
		Iterator val_it1=tmp_sess_info.values().iterator();

		while( sess_it1.hasNext() && val_it1.hasNext())
		{
			String sess_id=(String)sess_it1.next();
			String sess_user=(String)val_it1.next();
			if (orgSpecificUserList.contains(sess_user))
			{
				tmp_sess_info1.put(sess_id,sess_user);
			}
		}
	}
	else
	{
		if (eGMgrModel != null && eGMgrModel.equalsIgnoreCase("enterprise"))
		{
			orgSpecificUserList.addAll(egUuidInfo.getAllUsersUnderOrg("egenterprise"));
			Iterator sess_it1= tmp_sess_info.keySet().iterator();
			Iterator val_it1=tmp_sess_info.values().iterator();

			while( sess_it1.hasNext() && val_it1.hasNext())
			{
				String sess_id=(String)sess_it1.next();
				String sess_user=(String)val_it1.next();
				if (orgSpecificUserList.contains(sess_user))
				{
					tmp_sess_info1.put(sess_id,sess_user);
				}
			}
		}
		else
		{
			tmp_sess_info1.putAll(tmp_sess_info);
		}
	}

	Iterator sess_it= tmp_sess_info1.keySet().iterator();
	Iterator val_it=tmp_sess_info1.values().iterator();

	int sessionCount =  0; //tmp_sess_info1.size(); // Total users
	
	TreeSet ts=new TreeSet(tmp_sess_info1.values());
//	int unique_users = ts.size(); // Unique users
	Set uniqueUsersSet = new HashSet();
	String sortTypes[]={"Last Accessed Time","Login Time","User Name","Host IP"};
	String sortBy=request.getParameter("sort");
	String orderBy=request.getParameter("order");
	String number[]={"0","1"};
	if(StringUtils.isNull(orderBy))
	{
		orderBy=number[1];
	}
	if (StringUtils.isNull(sortBy))
	{
		sortBy=number[0];
	}

	Vector sort_v=new Vector();
	SimpleDateFormat simple=null;
	Vector sessionList=new Vector();
	String sessionValue="";
	String value="";
	String listOne="";
	String listTwo="";
	String sortTemp=sortBy;
	String stringValueOne="";
	String stringValueTwo="";
	Long longValueOne=null;
	Long longValueTwo=null;
	boolean swap=false;
	boolean cellFlag=false;
	boolean isLongDepend=false;
	int startIndex=0;
	int endIndex=0;
	int total=0;
	isLongDepend=(sortTemp.equals("0")||sortTemp.equals("1")||sortTemp.equals("3"));
	String uiFile = "eg_ui.ini";
	String s_iniFile_dir = EgInstallInfo.getInstallDir()+ "/manager/config/";
	IniFile egUI = new IniFile(s_iniFile_dir + uiFile);
	String currentDateFormat = egUI.getValue("CURRENT_DATE_FORMAT","selectedDateFormat");
	IniFile userMappingIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	geoLocationInformation geolocation = new geoLocationInformation();
	while( sess_it.hasNext() && val_it.hasNext())
	{
		JSONObject usersObj = new JSONObject();
		String sess_id=(String)sess_it.next();

		User userbj = userRregistry.getUser(sess_id);
		String sess_user=(String)val_it.next();
		String userType = (String)userbj.getLoginType();
		String temp_Usr = userMappingIni.getValue("DBUSER_USER_MAP",sess_user);
		if (temp_Usr != null && temp_Usr.length() > 0)
		{
			sess_user = temp_Usr;
		}
		if (sess_user != null && sess_user.indexOf("/Grp/") != -1)
		{
			String uname = sess_user;
			String grpDelimiter = "/Grp/";
			int idx = uname.indexOf(grpDelimiter);
			String str_uname_A = uname.substring(0,idx);
			int nextIdx = idx + grpDelimiter.length();
			String str_uname_B = uname.substring(nextIdx);
			uname = str_uname_A + "/" + str_uname_B + " (Group)";
			sess_user = (String)sessGrpUser.get(sess_id) + " {" + uname + "}";
		}
		else if (sess_user.startsWith("samlsso/"))
		{
			String tmp = sess_user;
			int idx = tmp.indexOf("/");
			tmp = tmp.substring(idx+1);
			tmp = tmp + " (SAML)";
			sess_user = tmp;
		}

		Long lt =(Long)userRregistry.sessionLoginTime.get(sess_id);
		Long lat = (Long)userRregistry.sessionLastTime.get(sess_id);
		String ip = (String)User.getUserIP(sess_id);
		if (ip != null && ip.equalsIgnoreCase("N/A"))
		{
			continue;
		}
		sessionCount++;
		ArrayList geoLocationList = geolocation.getGeoLocDetails(ip);
		String geolocationInfo = null;
		if(geoLocationList != null && geoLocationList.size() > 0){
			StringBuilder geoInfoStrBldr = new StringBuilder();
			int geoCount = 0;
			for(int k=3; k >= 0; k--){
				if(k == 1) continue;
				String geoValue = (String)geoLocationList.get(k);
				if(geoValue != null && !geoValue.equals("Unknown")){
					if(geoCount > 0){
						geoInfoStrBldr.append(", ");
					}
					geoInfoStrBldr.append(geoValue);
					geoCount++;
				}
			}
			geolocationInfo = geoInfoStrBldr.toString();
		}
		else{
			geolocationInfo = "Unknown";
		}
		if(geolocationInfo != null && geolocationInfo.length() == 0){
			geolocationInfo = "Unknown";
		}
		String tempSessUser = StringUtils.replace(sess_user,"<","&lt;");
		tempSessUser = StringUtils.replace(tempSessUser,">","&gt;");
		//tempSessUser = StringUtils.replace(tempSessUser,"[","|ocbr|");
		//tempSessUser = StringUtils.replace(tempSessUser,"]","|ccbr|");

		simple=new SimpleDateFormat(currentDateFormat+" HH:mm:ss");
		value = simple.format(new Date(lat.longValue()));
		com.egurkha.EgTimeZoneConverter egt = new com.egurkha.EgTimeZoneConverter(value, _user);
		String lastAccessedTime = egt.getDateTime();
		uniqueUsersSet.add(tempSessUser);
		simple = new SimpleDateFormat(currentDateFormat+" HH:mm:ss");
		value = simple.format(new Date(lt.longValue()));
		com.egurkha.EgTimeZoneConverter egt1 = new com.egurkha.EgTimeZoneConverter(value, _user);
		String loginTime = egt1.getDateTime();

		usersObj.put("Host IP",ip);
		usersObj.put("User name",tempSessUser);
		usersObj.put("User Role",userType);
		usersObj.put("LOGIN TIME",loginTime);
		usersObj.put("LAST ACCESSED TIME",lastAccessedTime);
		usersObj.put("Geo Location",geolocationInfo);
		tmpArray.add(usersObj);
	}
	int uniqueUsersCount = uniqueUsersSet.size();
	JSONArray gridColums = new JSONArray();
	gridColums.add(_mapping.getTextDescription("admin.usersession.Host IP"));
	gridColums.add(_mapping.getTextDescription("admin.usersession.User name"));
	gridColums.add(_mapping.getTextDescription("admin.usersession.User Role"));
	gridColums.add(_mapping.getTextDescription("admin.usersession.Login time"));
	gridColums.add(_mapping.getTextDescription("admin.usersession.Last accessed time"));
	gridColums.add(_mapping.getTextDescription("admin.usersession.Geo Location"));
	rootObj.put("gridColums",gridColums);
	rootObj.put("LoggedInUsers",tmpArray);
	rootObj.put("sessionCount",sessionCount);
	rootObj.put("unique_users",uniqueUsersCount);
	out.println(rootObj.toString());
%>




