<%@ include file="../../../admin/EgTrackerAJSON.jsp" %>

<%@ page import = "java.io.*" %>
<%@ page import = "java.util.*" %>
<%@ page import = "com.eg.IniFile" %>
<%@ page import = "com.eg.EgConfigFilesSync"%>
<%@ page import = "com.eg.EgInstallInfo" %>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.egurkha.User"%>
<%@ page import = "com.egurkha.UserRegistry"%>
<%@ page import = "net.sf.json.*"%>
<%@ page import = "com.egurkha.ini.IniUI"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import = "com.egurkha.admin.AuditLogThread"%>

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

<%
	JSONObject rootJson = new JSONObject();
	UserRegistry ur = UserRegistry.getInstance();
	User user = ur.getUser(sessionID);
	String username = user.getLoginID();
	IniFile clsIni = new IniFile (EgInstallInfo.getInstallDir()+"/manager/config/eg_ls_portal.ini");
	String defaultLS = clsIni.getValue("LS_TRIAL_SETTINGS","defaultLogonSimulator");
	String compType = "";
	if (defaultLS!=null && defaultLS.equalsIgnoreCase("all"))
	{
		compType = request.getParameter("compType");
	}
	else 
	{
		compType = defaultLS;
	}

	String userLanguage = _user.getLanguage();
	IniUI iniUI = IniUI.getInstance();
	if (userLanguage == null)
		userLanguage = iniUI.getDefaultLanguage();
	EgMappingInfo mapping = new EgMappingInfo(userLanguage);

	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","Logon Simulator Portal");

	String cls = clsIni.getValue("LS_TRIAL_USER_MAP",username);
	String testName = clsIni.getValue("Logon_Simulator",compType);
	String compName = "";
	ArrayList arr = new ArrayList();
	ArrayList al1 = new ArrayList();
	if (cls != null && cls.length() > 0)
	{
		StringTokenizer st = new StringTokenizer(cls,"$");
		String value0 = st.nextToken();
		String value = st.nextToken();
		if (value.indexOf('|') != -1)
		{
			StringTokenizer st1 = new StringTokenizer(value,"|");
			while (st1.hasMoreTokens())
			{
				String val = st1.nextToken();
				StringTokenizer st2 = new StringTokenizer(val,"#");
				while (st2.hasMoreTokens())
				{
					String tok = st2.nextToken();
					arr.add(tok);
				}
				for (int i=0 ; i < arr.size(); i++)
				{
					if (((String)arr.get(i)).equalsIgnoreCase(compType))
					{
						compName = (String)arr.get(i+1);
						break;
					}
				}
			}
		}
		else
		{
			StringTokenizer st3 = new StringTokenizer(value,"#");
			while (st3.hasMoreTokens())
			{
				String tok1 = st3.nextToken();
				al1.add(tok1);
			}
			if (((String)al1.get(0)).equalsIgnoreCase(compType))
			{
				compName = (String)al1.get(1);
			}
		}
	}
	String comeFrom = request.getParameter("comeFrom");
	if (compName != null && compName.length() > 0)
	{
		if (comeFrom != null && comeFrom.equalsIgnoreCase("view"))
		{
			IniFile agentIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini",true);
			String agentIniVariables[] = agentIni.getVariables(compName);
			ArrayList al = new ArrayList();
			for (int i=0; i<agentIniVariables.length ; i++)
			{
				if (agentIniVariables[i].indexOf(testName+"::"+compName) != -1)
				{
					String iniValue =  agentIni.getValue(compName,agentIniVariables[i]);
					StringTokenizer testVal = new StringTokenizer(iniValue,",");
					testVal.nextToken();
					String reqTestVal = testVal.nextToken();
					al = getParameterList(reqTestVal,false);
					for (int j=0;j<al.size();j=j+2)
					{
						String strParamName = (String)al.get(j);
						String strSearch = strParamName.substring(1);
						String strParamValue = (String)al.get(j+1);
						if (strSearch.indexOf("Site_url") != -1)
						{
							rootJson.put("Site_url",strParamValue);
						}
						else if (strSearch.indexOf("Published_resources") != -1)
						{
							if (strParamValue.startsWith("\"") && strParamValue.endsWith("\""))
							{
								strParamValue = strParamValue.substring(1,strParamValue.length()-1);
							}
							rootJson.put("Published_resources",strParamValue);
						}
						else if (strSearch.indexOf("Username") != -1)
						{
							rootJson.put("Username",strParamValue);
						}
						else if (strSearch.indexOf("Password") != -1)
						{
							rootJson.put("Password",EgCrypt.decrypt(strParamValue));
						}
						else if (strSearch.indexOf("Domain") != -1)
						{
							rootJson.put("Domain",strParamValue);
						}
						else if (strSearch.indexOf("Two_factor_auth_password") != -1)
						{
							rootJson.put("Two_FA",EgCrypt.decrypt(strParamValue));
						}
						else if (strSearch.indexOf("Browser_type") != -1)
						{
							rootJson.put("showAll",true);
							rootJson.put("Browser_type",strParamValue);
						}
						else if (strSearch.indexOf("Disclaimer") != -1)
						{
							rootJson.put("Disclaimer",strParamValue);
						}
						else if (compType.equalsIgnoreCase("Citrix_XcLogon_Emulation") && strSearch.indexOf("Citrix_cloud_workspace") != -1)
						{
							rootJson.put("Citrix_cloud_workspace",strParamValue);
						}
					}
				}
			}
			JSONObject jsonObj = new JSONObject();
			JSONArray jsonArr = new JSONArray();

			String browserType = clsIni.getValue("LS_TRIAL_SETTINGS","defaultBrowserType");
			if (browserType != null && !browserType.equalsIgnoreCase("all"))
			{
				rootJson.put("showAll",false);
				rootJson.put("Browser_type",browserType);
				jsonObj.put("displayField",browserType);
				jsonObj.put("valueField",browserType);
				jsonArr.add(jsonObj);
			}
			else
			{
				jsonObj.put("displayField","Chrome");
				jsonObj.put("valueField","Chrome");
				jsonArr.add(jsonObj);
				jsonObj.put("displayField","IE");
				jsonObj.put("valueField","IE");
				jsonArr.add(jsonObj);
			}
			rootJson.put("listOfBrowser",jsonArr);
		}
		else if (comeFrom != null && comeFrom.equalsIgnoreCase("update"))
		{
			String hiddenPublishSrcVal = request.getParameter("hiddenPublishSrcVal");
			String multiUsrdomainVal = request.getParameter("multiUsrdomainVal");
			String multiUsrVal = request.getParameter("multiUsrVal");
			String multiUsrpassVal = request.getParameter("Password");
			String siteUrl = request.getParameter("siteUrl");
			String browserType = request.getParameter("browserType");
			String multi2FAuthVal = request.getParameter("Two_factor_auth_password");
			String multiUsrdisclaimVal = request.getParameter("multiUsrdisclaimVal");
			String ctxCloudWrkSpace = request.getParameter("ctxCloudWrkSpace");

			IniFile agentIni1 = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_agents.ini",true);
			String agentIniVariables1[] = agentIni1.getVariables(compName);
			ArrayList aList = new ArrayList();
			ArrayList aListFinal = new ArrayList();
			String finalparamValue = "";
			for (int i=0; i<agentIniVariables1.length ; i++)
			{
				if (agentIniVariables1[i].indexOf(testName+"::"+compName) != -1)
				{
					String iniValue1 =  agentIni1.getValue(compName,agentIniVariables1[i]);
					StringTokenizer testVal1 = new StringTokenizer(iniValue1,",");
					testVal1.nextToken();
					String reqTestVal1 = testVal1.nextToken();
					String timePeriod = testVal1.nextToken();
					timePeriod = timePeriod.trim();
					aList = getParameterList(reqTestVal1,false);
					aListFinal.add("-manual,");
					for (int k=0;k<aList.size();k=k+2)
					{
						String paramName = (String)aList.get(k);
						String paramValue = (String)aList.get(k+1);
						if (paramName.indexOf("-Site_url") != -1)
						{
							finalparamValue = siteUrl;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else if (paramName.indexOf("-Published_resources") != -1)
						{
							finalparamValue = hiddenPublishSrcVal;
							aListFinal.add(paramName);
							if (finalparamValue.indexOf(" -") > -1 || finalparamValue.startsWith(" ") || finalparamValue.endsWith(" "))
							{
								finalparamValue = "\"" + finalparamValue + "\"";
							}
							aListFinal.add(finalparamValue);
						}
						else if (paramName.indexOf("-Domain") != -1)
						{
							finalparamValue = multiUsrdomainVal;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else if (paramName.indexOf("-Username") != -1)
						{
							finalparamValue = multiUsrVal;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else if (paramName.indexOf("-Password") != -1)
						{
							finalparamValue = multiUsrpassVal;
							aListFinal.add(paramName);
							aListFinal.add(EgCrypt.encrypt(finalparamValue));
						}
						else if (paramName.indexOf("-Two_factor_auth_password") != -1)
						{
							finalparamValue = multi2FAuthVal;
							aListFinal.add(paramName);
							aListFinal.add(EgCrypt.encrypt(finalparamValue));
						}
						else if (paramName.indexOf("-Browser_type") != -1)
						{
							finalparamValue = browserType;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else if (paramName.indexOf("-Disclaimer") != -1)
						{
							finalparamValue = multiUsrdisclaimVal;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else if (compType.equalsIgnoreCase("Citrix_XcLogon_Emulation") && paramName.indexOf("-Citrix_cloud_workspace") != -1)
						{
							finalparamValue = ctxCloudWrkSpace;
							aListFinal.add(paramName);
							aListFinal.add(finalparamValue);
						}
						else
						{
							aListFinal.add(paramName);
							aListFinal.add(paramValue);
						}
					}
				
					String strValue = "";
					for (int l=0;l<aListFinal.size();l++)
					{
						strValue = strValue +(String)aListFinal.get(l)+" ";
					}
					strValue = strValue.trim();
					strValue = strValue + ", " + timePeriod;
					
					if (compType.equalsIgnoreCase("Citrix_XcLogon_Emulation"))
					{
						if (strValue.indexOf("-Citrix_cloud_workspace") == -1)
						{
							String firstPart = strValue.substring(0,strValue.indexOf("-Use_ica"));
							String secondPart = strValue.substring(strValue.indexOf("-Use_ica"),strValue.length());
							String finalStr = firstPart.trim() + " -Citrix_cloud_workspace " + ctxCloudWrkSpace + " "+ secondPart.trim();
							strValue = finalStr;
						}
					}
					agentIni1.setValue(compName,agentIniVariables1[i],strValue);
					agentIni1.saveFile();
				}
				EgConfigFilesSync.releaseInstance(agentIni1);
			}

			IniFile clsIni_write = EgConfigFilesSync.getInstance(EgInstallInfo.getInstallDir() + "/manager/config/eg_ls_portal.ini",true);
			String val = clsIni_write.getValue("LS_TRIAL_USER_MAP",username);
			StringTokenizer st = new StringTokenizer(cls,"$");
			String avalue = st.nextToken();
			String temp = st.nextToken();
			ArrayList alist = new ArrayList();
			if (temp!=null && temp.length() > 0)
			{
				if (temp.indexOf('|') != -1)
				{
					StringTokenizer st1 = new StringTokenizer(temp,"|");
					int st1Count = st1.countTokens();
					
					while (st1.hasMoreTokens())
					{
						String val1 = st1.nextToken();
						StringTokenizer stok = new StringTokenizer(val1,"#");
						int stokCount = stok.countTokens();
						while (stok.hasMoreTokens())
						{
							String tok = stok.nextToken();
							alist.add(tok);
						}
						for (int i=0 ; i<alist.size() ; i++)
						{
							if (((String)alist.get(i)).equalsIgnoreCase(compType))
							{
								alist.set(i+2,"Yes");
							}
						}
					}
					String newVal = avalue+"$";
					for (int i=0 ; i<alist.size() ; i++)
					{
						if (((String)alist.get(i)).equalsIgnoreCase("yes") || ((String)alist.get(i)).equalsIgnoreCase("no"))
						{
							newVal = newVal + (String)alist.get(i) + "|";
						}
						else
						{
							newVal = newVal + (String)alist.get(i) + "#";
						}
					}
					newVal = newVal.substring(0,newVal.length()-1);
					clsIni_write.setValue("LS_TRIAL_USER_MAP",username,newVal);
				}
				else
				{
					StringTokenizer st3 = new StringTokenizer(temp,"#");
					while (st3.hasMoreTokens())
					{
						String tok1 = st3.nextToken();
						alist.add(tok1);
					}
					if (((String)alist.get(0)).equalsIgnoreCase(compType))
					{
						alist.set(2,"Yes");
					}
					String newVal = avalue+"$";
					for (int i=0 ; i<alist.size() ; i++)
					{
						newVal = newVal + (String)alist.get(i) +"#";
					}
					newVal = newVal.substring(0,newVal.length()-1);
					clsIni_write.setValue("LS_TRIAL_USER_MAP",username,newVal);
				}
				rootJson.put("agentDownload",avalue);
			}
			clsIni_write.saveFile();
			EgConfigFilesSync.releaseInstance(clsIni_write);
			
			hiddenPublishSrcVal = StringUtils.replace(hiddenPublishSrcVal,"~#~",";");

			auditLogThread.setValue("Activity","Configure Simulation");
			auditLogThread.setValue("Description","Test "+mapping.getTestDescription(testName)+" for component "+compName+" of type "+mapping.getComponentTypeDescription(compType)+" has been configured");
			auditLogThread.setCurrentValue("01~~HOST", compName);
			auditLogThread.setCurrentValue("02~~SITE_URL", siteUrl);
			auditLogThread.setCurrentValue("03~~BROWSER_TYPE", browserType);
			if (hiddenPublishSrcVal.indexOf("|") != -1)
			{
				StringTokenizer stz = new StringTokenizer(hiddenPublishSrcVal,"|");
				while (stz.hasMoreTokens())
				{
					auditLogThread.setCurrentValue("04~~PUBLISHED_RESOURCES", stz.nextToken());
				}
				StringTokenizer stz1 = new StringTokenizer(multiUsrVal,"|");
				while (stz1.hasMoreTokens())
				{
					auditLogThread.setCurrentValue("05~~USERNAME", stz1.nextToken());
				}
				StringTokenizer stz2 = new StringTokenizer(multiUsrdomainVal,"|");
				while (stz2.hasMoreTokens())
				{
					auditLogThread.setCurrentValue("06~~DOMAIN", stz2.nextToken());
				}
				StringTokenizer stz3 = new StringTokenizer(multiUsrdisclaimVal,"|");
				while (stz3.hasMoreTokens())
				{
					auditLogThread.setCurrentValue("07~~DISCLAIMER", stz3.nextToken());
				}
			}
			else
			{
				auditLogThread.setCurrentValue("04~~PUBLISHED_RESOURCES", hiddenPublishSrcVal);
				auditLogThread.setCurrentValue("05~~USERNAME", multiUsrVal);
				auditLogThread.setCurrentValue("06~~DOMAIN", multiUsrdomainVal);
				auditLogThread.setCurrentValue("07~~DISCLAIMER", multiUsrdisclaimVal);
			}

			if (compType.equalsIgnoreCase("Citrix_XcLogon_Emulation"))
			{
				auditLogThread.setCurrentValue("08~~CITRIX_CLOUD_WORKSPACE",ctxCloudWrkSpace);
			}
			auditLogThread.sendItToDB();
		}
	}
	out.println(rootJson.toString());

%>

<%!
	private ArrayList getParameterList(String str,boolean needLowerCaseKey)
	{
		String delimiter = " -";
		ArrayList aListResultant = new ArrayList();
		String prevKey = "";

		str = str.substring(str.indexOf("-"));
		int spaceHyphenIdx = str.indexOf(delimiter);
		while (spaceHyphenIdx != -1)
		{
			String cutString = str.substring(0,spaceHyphenIdx);

			//This check will be carried out when the cutString contains only the key
			//for e.g.:-
			//str : -admin_password -103:98:88:90:79:76:81:-110:52 -ssl false
			//cutString : -admin_password
			if (cutString.trim().indexOf(" ") == -1)
			{
				String strPart1 = str.substring(cutString.length()+1);
				String strPart2 = strPart1.substring(0,strPart1.indexOf(delimiter));
				cutString = cutString+" "+strPart2;
				spaceHyphenIdx = cutString.length();
			}

			if (cutString.indexOf("\"") != -1)
			{
				String strAfterDoubleQuotes = str.substring(spaceHyphenIdx);
				String remainingPiece = strAfterDoubleQuotes.substring(0,strAfterDoubleQuotes.indexOf("\"")+1);
				cutString = cutString + remainingPiece;

				String key = cutString.substring(0,cutString.indexOf(" "));
				String value = cutString.substring(cutString.indexOf(" ")+1);
				if (needLowerCaseKey)
				{
					aListResultant.add(key.trim().toLowerCase());
				}
				else
				{
					aListResultant.add(key.trim());
				}
				aListResultant.add(value.trim());

				String remainingString = strAfterDoubleQuotes.substring(strAfterDoubleQuotes.indexOf("\"")+1);
				str = remainingString.trim();
				if (str.length() == 0)
				{
					spaceHyphenIdx = -1;
				}
				else
				{
					spaceHyphenIdx = str.indexOf(delimiter);
				}
			}
			else
			{
				if (cutString.startsWith("- "))
				{
					int idx = aListResultant.indexOf(prevKey);
					String strValue = (String)aListResultant.get(idx+1);
					strValue = strValue + " " + cutString;
					aListResultant.remove(idx+1);
					aListResultant.add(strValue);

					str = str.substring(cutString.length()+1);
				}
				else
				{
					String key = cutString.substring(0,cutString.indexOf(" "));
					String value = cutString.substring(cutString.indexOf(" ")+1);
					if (needLowerCaseKey)
					{
						aListResultant.add(key.trim().toLowerCase());
						prevKey = key.trim().toLowerCase();
					}
					else
					{
						aListResultant.add(key.trim());
						prevKey = key.trim();
					}
					aListResultant.add(value.trim());

					str = str.substring(spaceHyphenIdx+1);
				}
				spaceHyphenIdx = str.indexOf(delimiter);
			}
		}

		if (str.length() > 0)
		{
			if (str.startsWith("- "))
			{
				int idx = aListResultant.indexOf(prevKey);
				String strValue = (String)aListResultant.get(idx+1);
				strValue = strValue + " " + str;
				aListResultant.remove(idx+1);
				aListResultant.add(strValue);
			}
			else
			{
				String lastKey = str.substring(0,str.indexOf(" "));
				String lastValue = str.substring(str.indexOf(" ")+1);
				if (needLowerCaseKey)
				{
					aListResultant.add(lastKey.trim().toLowerCase());
				}
				else
				{
					aListResultant.add(lastKey.trim());
				}
				aListResultant.add(lastValue.trim());
			}
		}

		return aListResultant;
	}
%>



