<%
/*
 *   File		:	EgApplyToOtherComponents.jsp
 *   Purpose	:	To view and configure tests for other components
 *   Author		:	S.Anand (2008)
 *   UI Design	:	Jaiwin & Krishnamurthi
*/
%>

<%@ include file="../../EgTrackerAJSON.jsp" %>
<%@page import="java.util.*"%>
<%@ page import="com.eg.EgRoleInfo" %>
<%@ page import="com.eg.EgSpecsInfo" %>
<%@ page import="com.eg.EgGroupInfo" %>
<%@ page import="com.eg.EgTopoInfo" %>
<%@ page import="com.egurkha.ini.IniUI" %>
<%@ page import="com.egurkha.util.*" %>
<%@ page import="net.sf.json.*"%>

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

<jsp:useBean id="prgBean" scope="page" class="egurkha.EgTestParamBean"/>

<%
	JSONObject rootJson = new JSONObject();
	JSONObject hiddenObj = new JSONObject();

	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
%>

<%!

	public ArrayList tokenizeInfo(String str)
	{
		ArrayList al = new ArrayList();
		StringTokenizer st = new StringTokenizer(str, ",");
		int count = st.countTokens();
		for(int i=0; i<count; i++)
		{
			al.add(st.nextToken().trim());
		}
		return al;
	}

	public static ArrayList breakString(String givenString,int screenLen)
	{
		ArrayList aListResultant = new ArrayList();
		int strLen = givenString.length();
		int resLen = strLen/screenLen;
		int idx = 0;
		int k = 0;
		if (givenString.indexOf(" ")>-1)
		{
			for (int i=0;i<resLen;i++)
			{
				String res = givenString.substring(idx,idx+screenLen);
				int s = res.length();
				if (res.charAt(s-1)==' ')
				{
					res = res.trim();
					aListResultant.add(res);
					idx = idx+screenLen;
				}
				else
				{
					k = res.lastIndexOf(" ");
					if (k==0 || k == -1)
					{
						aListResultant.add(res.substring(0));
						idx = idx+screenLen;
					}
					else
					{
						aListResultant.add(res.substring(0,k));
						String temp = res.substring(k);
						int m = temp.length();
						idx = idx+screenLen;
						idx = idx-m;
					}
				}
				if (i == resLen-1)
				{
					int lastLen = strLen-idx;
					if (lastLen > screenLen)
					{
						resLen = resLen+1;
					}
				}
			}
			String ss = givenString.substring(idx).trim();
			aListResultant.add(ss);
		}
		else
		{
			for (int i=0;i<resLen ;i++)
			{
				String res = givenString.substring(idx,idx+screenLen);
				aListResultant.add(res);
				idx = idx+screenLen;
			}
			aListResultant.add(givenString.substring(idx));
		}
		return aListResultant;
	}

%>

<%

	EgSpecsInfo egSpecs = new EgSpecsInfo("manager");

	String fromPage = request.getParameter("requestFrom");
	fromPage = (fromPage == null)?"EgConfigureComponentTests.jsp":fromPage;

	Hashtable otherCompDetails = new Hashtable();

	//datas needed for processing page - starts
	String componentType = null;
	String componentName = null;
	String testName = null;
	String testPeriod = null;
	String strEnabledDesc = null;
	String strDisabledDesc = null;
	ArrayList aListTemp1 = new ArrayList();

	IniFile testInfoIni = new IniFile(EgConfigInfo.egMgrConfigDir + "eg_testinfo.ini");
	String showApplyToOtherComponentsList = testInfoIni.getValue("MISC_ARGS","ShowInApplyToOtherComponentsList");
	if(showApplyToOtherComponentsList == null)
	{
		showApplyToOtherComponentsList = "Manangedcomponents";
	}

	if (fromPage.equals("EgConfigureComponentTests.jsp"))
	{
		otherCompDetails = (Hashtable) session.getAttribute("otherCompDetails");

		componentType = request.getParameter("componentType");
		componentName = request.getParameter("componentName");
		testName = request.getParameter("testName");
		testPeriod = request.getParameter("testPeriod");
		strEnabledDesc = request.getParameter("enabledDescList");
		strDisabledDesc = request.getParameter("disabledDescList");
	}
	else
	{
		Hashtable hashParamNamesAndValuesTemp = (Hashtable)session.getAttribute("hashParamNamesAndValues");
		otherCompDetails = (Hashtable)session.getAttribute("otherCompDetails");
		componentType = (String)hashParamNamesAndValuesTemp.get("componentType");
		componentName = (String)hashParamNamesAndValuesTemp.get("componentName");
		testName = (String)hashParamNamesAndValuesTemp.get("testName");
		testPeriod = (String)hashParamNamesAndValuesTemp.get("testPeriod");
		strDisabledDesc = (String)hashParamNamesAndValuesTemp.get("disabledDescList");
		strEnabledDesc = (String)hashParamNamesAndValuesTemp.get("enabledDescList");
	}

	boolean isPortRelevantForTest = egSpecs.isPortRelevantForTest(testName);
	String displayComponentName = componentName.substring(componentName.indexOf(":")+1);
	if (displayComponentName.indexOf(":NULL") > -1)
	{
		displayComponentName = displayComponentName.substring(0,displayComponentName.indexOf(":"));
	}

	if (fromPage.equals("EgConfigureComponentTests.jsp"))
	{
		Enumeration e1 = request.getParameterNames();
		while (e1.hasMoreElements())
		{
			String strParamName = (String)e1.nextElement();
			String strParamValue = request.getParameter(strParamName);
			boolean isPasswordParameter = false;
			boolean allowToTrim = true;

			//a line feed ('\n') or enter key
			while(strParamValue.indexOf("\n") > -1)
			{
				int idx = strParamValue.indexOf("\n");
				String strPrefix = strParamValue.substring(0,idx-1);
				String strSuffix = strParamValue.substring(idx+1,strParamValue.length());
				strSuffix = strSuffix.trim();
				strParamValue = strPrefix + strSuffix;
			}



			aListTemp1.add("-"+strParamName);
			if (allowToTrim)
			{
				strParamValue = strParamValue.trim();
			}
			aListTemp1.add(strParamValue);
		}

		Hashtable hashParamNamesAndValues = new Hashtable();
		hashParamNamesAndValues.put("componentType",componentType);
		hashParamNamesAndValues.put("componentName",componentName);
		hashParamNamesAndValues.put("testName",testName);
		hashParamNamesAndValues.put("testPeriod",testPeriod);
		hashParamNamesAndValues.put("disabledDescList",strDisabledDesc);
		hashParamNamesAndValues.put("enabledDescList",strEnabledDesc);
		hashParamNamesAndValues.put("otherCompDetails",otherCompDetails);

		session.setAttribute("hashParamNamesAndValues",hashParamNamesAndValues);
	}
	//datas needed for processing page - ends

	//tells information about the corresponding authenticated user
	EgRoleInfo ri = EgRoleInfo.getInstance(session.getId(),(String)session.getAttribute("sess_userid"));

	String[] componentsList = null;
	ArrayList aListExpectedComponents = new ArrayList();
	ArrayList aListParamNamesAndValues = new ArrayList();
	ArrayList enabledDescList = StringUtils.egTokenizer(strEnabledDesc,",");
	ArrayList disabledDescList = StringUtils.egTokenizer(strDisabledDesc,",");

	if (disabledDescList != null && !disabledDescList.isEmpty())
	{
		for(int d=0;d<disabledDescList.size();d++)
		{
			aListParamNamesAndValues.add(disabledDescList.get(d).toString());
			aListParamNamesAndValues.add("Disable");
		}
	}

	if (enabledDescList != null && !enabledDescList.isEmpty())
	{
		for(int e=0;e<enabledDescList.size();e++)
		{
			aListParamNamesAndValues.add(enabledDescList.get(e).toString());
			aListParamNamesAndValues.add("Enable");
		}
	}

	ArrayList aListDisplayParamNameAndValues = new ArrayList();
	if (componentType != null && !componentType.equals(""))
	{
		componentsList = ri.getAllServersOfType(componentType);
		Arrays.sort(componentsList);
	}

	if (otherCompDetails != null && !otherCompDetails.isEmpty())
	{
		HashSet tmpCompsList = new HashSet();
		HashSet otherRunningCompsList = new HashSet();
		Iterator keys = otherCompDetails.keySet().iterator();
		while(keys.hasNext())
		{
			String strCompKey = (String) keys.next();
			if(strCompKey.startsWith(componentType))
			{
				String hashTestVals = (String) otherCompDetails.get(strCompKey);
				int delim = hashTestVals.indexOf("0eGHash1");
				int sepLen = "0eGHash1".length();

				otherRunningCompsList.add(strCompKey); // getting running comp list
				String earlierDisableInfo = "";
				String strOtherInfos = "";
				if(delim >= 0)
				{
					strOtherInfos = hashTestVals.substring(0, delim);
					earlierDisableInfo = hashTestVals.substring(delim+sepLen);
				}
				else
				{
					strOtherInfos = hashTestVals;
				}

				ArrayList earlierDisableInfoList = tokenizeInfo(earlierDisableInfo);
				ArrayList otherInfosList = tokenizeInfo(strOtherInfos);
				if (enabledDescList != null && !enabledDescList.isEmpty())
				{
					earlierDisableInfoList.retainAll(enabledDescList);
					if (earlierDisableInfoList != null && !earlierDisableInfoList.isEmpty())
					{
						tmpCompsList.add(strCompKey);
					}
				}

				if (disabledDescList != null && !disabledDescList.isEmpty())
				{
					otherInfosList.retainAll(disabledDescList);
					if (otherInfosList != null && !otherInfosList.isEmpty())
					{
						tmpCompsList.add(strCompKey); //no break, looping entire hashtable
					}
				}


				//strCompKey = strCompKey.substring(0,strCompKey.indexOf("#"));

			}
		}

		if (showApplyToOtherComponentsList.equalsIgnoreCase("runningcomponents"))
		{
			if (tmpCompsList != null && !tmpCompsList.isEmpty())
			{
				componentsList =  (String[]) tmpCompsList.toArray(new String[tmpCompsList.size()]);
				Arrays.sort(componentsList);
			}
			else if (otherRunningCompsList != null && !otherRunningCompsList.isEmpty())
			{
				componentsList =  (String[]) otherRunningCompsList.toArray(new String[otherRunningCompsList.size()]);
				Arrays.sort(componentsList);
			}
		}

	}
	for(int i=0;i<componentsList.length;i++)
	{
		String strComp = componentsList[i];
		String strCompName = strComp.substring(strComp.indexOf(":")+1,strComp.length());

		if (strComp.equals(componentName)) continue;
		aListExpectedComponents.add(strComp);
	}

	//remove the component from the aListExpectedComponents whose test is excluded - starts
	ArrayList aListTempExpectedComponents = new ArrayList(aListExpectedComponents);
	prgBean.createFile("eg_disable.ini");
	if (isPortRelevantForTest)
	{
		String[] variables = prgBean.getVariables(componentType);
		ArrayList aListVariables = new ArrayList(Arrays.asList(variables));
		for (int i=0;i<aListExpectedComponents.size();i++)
		{
			String tempComp = (String)aListExpectedComponents.get(i);
			String pattern = tempComp;
			if (aListVariables.contains(pattern))
			{
				String value = prgBean.getStrValue(componentType,pattern);
				if (value.indexOf(",") == -1)
				{
					if (value.equals(testName))
					{
						aListTempExpectedComponents.remove(tempComp);
					}
				}
				else
				{
					if (!StringUtils.isNull(value))
					{
						ArrayList valueList = StringUtils.egTokenizer(value,",");
						if (valueList != null && valueList.contains(testName))
						{
							aListTempExpectedComponents.remove(tempComp);
						}
					}
				}
			}
		}
	}
	else
	{
		String[] variables = prgBean.getVariables("Default_server");
		ArrayList aListVariables = new ArrayList(Arrays.asList(variables));
		for (int i=0;i<aListExpectedComponents.size();i++)
		{
			String tempComp = (String)aListExpectedComponents.get(i);
			String strCompName = tempComp.substring(tempComp.indexOf(":")+1,tempComp.length());
			String pattern = "Default_server:"+strCompName.substring(0,strCompName.indexOf(":"));
			if (aListVariables.contains(pattern))
			{
				String value = prgBean.getStrValue("Default_server",pattern);
				if (value.indexOf(",") == -1)
				{
					if (value.equals(testName))
					{
						aListTempExpectedComponents.remove(tempComp);
					}
				}
				else
				{
					if (!StringUtils.isNull(value))
					{
						ArrayList valueList = StringUtils.egTokenizer(value,",");
						if (valueList != null && valueList.contains(testName))
						{
							aListTempExpectedComponents.remove(tempComp);
						}
					}
				}
			}
		}
	}
	aListExpectedComponents = aListTempExpectedComponents;
	//remove the component from the aListExpectedComponents whose test is excluded - ends

	//building the parameter names and values which should be shown in ui - starts
	for(int i=0;i<aListParamNamesAndValues.size();i=i+2)
	{
		String tempParamName = (String)aListParamNamesAndValues.get(i);

		String tempParamValue = (String)aListParamNamesAndValues.get(i+1);
		aListDisplayParamNameAndValues.add(tempParamName);
		aListDisplayParamNameAndValues.add(tempParamValue);
	}
	//building the parameter names and values which should be shown in ui - ends

	String ea_criteria = request.getParameter("criteria");
	if (ea_criteria == null)
	{
		ea_criteria = "Component";
	}

	String ea_userOption = request.getParameter("userOption");
	if (StringUtils.isNull(ea_userOption) || ea_userOption.equals("-1"))
	{
		ea_userOption = null;
	}


	EgGroupInfo egGroupInfo = new EgGroupInfo();
	EgTopoInfo egTopoInfo = egGroupInfo.getTopoInfoObject();
	Vector vecUserOptions = null;
	ArrayList aListAssociatedComponents = new ArrayList();

	String allParamsChecked = "checked";
	ArrayList aListSelectedParameters = null;
	String selectedParameters = request.getParameter("selectedParameters");
	if (selectedParameters != null)
	{
		aListSelectedParameters = new ArrayList();
		StringTokenizer st = new StringTokenizer(selectedParameters,",");
		while(st.hasMoreTokens())
		{
			String credentialToken = st.nextToken();
			aListSelectedParameters.add(credentialToken.substring(1));
		}
		for(int i=0;i<aListDisplayParamNameAndValues.size();i=i+2)
		{
			String strDisplayName = (String)aListDisplayParamNameAndValues.get(i);
			if (aListSelectedParameters != null && !aListSelectedParameters.contains(strDisplayName))
			{
				allParamsChecked = "";
				break;
			}
		}
	}

	rootJson.put("gridTitle", _mapping.getTextDescription("admin.test.Descriptor(s) of")+"&nbsp;"+_mapping.getTestDescription(testName)+"&nbsp;test&nbsp;|&nbsp;Chosen&nbsp;component&nbsp;:&nbsp;"+displayComponentName+"&nbsp;("+_mapping.getComponentTypeDescription(componentType)+")");

	String title1 = "Components";
	if (!ea_criteria.equalsIgnoreCase("Component"))
	{
		title1 = _mapping.getTextDescription("admin.service.Components of")+ "&nbsp;"+ea_userOption+ "&nbsp;"+ea_criteria.toLowerCase();
	}

	rootJson.put("fieldSetTitle", title1);
	//rootJson.put("displayComponentName",displayComponentName+"&nbsp;("+_mapping.getComponentTypeDescription(componentType)+")");
	//rootJson.put("allParamsChecked",allParamsChecked);

	JSONObject paramsGridObj = new JSONObject();
	JSONArray paramsGridArr = new JSONArray();
	for(int i=0;i<aListDisplayParamNameAndValues.size();i=i+2)
	{
		String strDisplayName = (String)aListDisplayParamNameAndValues.get(i);
		String changeDispName = strDisplayName;

		String strChecked = "checked";
		if (!fromPage.equals("EgConfigureComponentTests.jsp"))
		{
			if (aListSelectedParameters != null && !aListSelectedParameters.contains(strDisplayName))
			{
				strChecked = "";
			}
		}
		paramsGridObj.put("DescriptorName",strDisplayName);
		paramsGridObj.put("valueField",strDisplayName);
		String value = (String)aListDisplayParamNameAndValues.get(i+1);

		if (value.length() < 85)
		{
			paramsGridObj.put("Action",value);

		}
		else
		{
			paramsGridObj.put("Action",value);
			ArrayList aListBreakString = breakString(value,85);
			for (int j=0; j<aListBreakString.size(); j++)
			{
			}
		}
		paramsGridArr.add(paramsGridObj);
	}
	rootJson.put("paramsGridArr",paramsGridArr);

	JSONObject unmanServersObj = new JSONObject();
	JSONArray unmanServersArr = new JSONArray();
	for (int i=0;i<aListExpectedComponents.size();i++)
	{
		String strComponent = (String)aListExpectedComponents.get(i);
		//strComponent = strComponent.substring(strComponent.indexOf(":")+1,strComponent.length());
		String str = strComponent.substring(strComponent.indexOf(":")+1,strComponent.length());;
		if (str.indexOf(":NULL") > -1)
		{
			str = str.substring(0,str.indexOf(":"));
		}
		unmanServersObj.put("valueField",strComponent);
		unmanServersObj.put("displayField",str);
		unmanServersArr.add(unmanServersObj);
	}
	rootJson.put("unmanServersArr",unmanServersArr);

	rootJson.put("compName",componentName);
	rootJson.put("testName",testName);
	rootJson.put("server",componentType);
	rootJson.put("duration",testPeriod);

	rootJson.put("enabledDescList",strEnabledDesc);
	rootJson.put("disabledDescList",strDisabledDesc);

	hiddenObj.put("requestFrom","EgApplyToOtherComponents.jsp");
	hiddenObj.put("criteriaPrevious",ea_criteria);
	hiddenObj.put("userOptionPrevious",ea_userOption);
	rootJson.put("applyAllHiddenObj",hiddenObj);
	out.println(rootJson.toString());

%>




