<%
/********************************************************************************************************
*	Name			:	services.jsp
*	Purpose			:	This jsp is used to display all the Segments and its associated components in Segment Dashboard
*	Version			:	5.6
*	CreationDate	:	Feb 20, 2012
*	Author			:	S.Saravanan
*******************************************************************************************************/
%>
<%@ include file = "EgMonitorTracker.jsp" %>
<%@ page errorPage="EgErrorSmall.jsp" %>
<%@ page import = "com.egurkha.*" %>
<%@ page import = "com.egurkha.monitor.*" %>
<%@ page import = "com.eg.EgURLEncoder" %>
<%@ page import = "java.util.*" %>
<%@ page import = "com.egurkha.ini.*" %>
<%@ taglib prefix="egui" uri="../WEB-INF/eg-taglib.tld" %>
<%@ page import = "com.eg.EgMappingInfo"%>
<%@ page import = "com.eg.EgTopoInfo"%>
<%@ page import = "com.eg.EgStateZone"%>
<%@ page import="com.eg.IniFile"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.EgDateInfo"%>
<%@ page import = "com.eg.EgMaintenanceInfo"%>
<%@ page import="com.egurkha.util.*"%>
<%@ page import="com.egurkha.admin.EgMaintenanceUtility"%>
<%@ page import = "net.sf.json.*" %>
<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%!
	JSONObject json = null;
	JSONArray rootItem = null, innerItem = null;
	JSONObject labelObject = new JSONObject();
%>
<%
try
{
	String segment_image = "";
	session.removeAttribute("layer");
	session.removeAttribute("test");
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader ("Expires", -1);
	response.setContentType("application/json");

	CompositeComparator compobj = new CompositeComparator();
	compobj.add(new StateComparatorDes());
	compobj.add(new NameComparatorAsc());
	SegmentListData d = (SegmentListData) request.getAttribute("data");
	SegmentListResult r = (SegmentListResult) request.getAttribute("result");
	if(session.getAttribute("SegmentListData")!=null && session.getAttribute("SegmentListResult")!=null)
	{
		d=(SegmentListData)session.getAttribute("SegmentListData");
		r=(SegmentListResult)session.getAttribute("SegmentListResult");
	}
	int normalSegmentCount=0;
	int abnormalSegmentCount=(r==null?0:r.segmentList.size());
	int totSegments = (r==null?0:r.segmentList.size());
	boolean ifshowImage=(r==null?false:r.showImage);
	String treeFlag=request.getParameter("treeFlag");

	IniUI iniUI = IniUI.getInstance();
	UserRegistry userReg = UserRegistry.getInstance();
	User user = userReg.getUser(session.getId());
	String thisLanguage = iniUI.getDefaultLanguage();
	if (user!=null)
	{
		String userLang = user.getLanguage();
		if (userLang!=null && !userLang.equalsIgnoreCase("NULL"))
		{
			thisLanguage=userLang;
		}
	}
	boolean isUserLanguageEnglish=true;
	if(thisLanguage!=null && !thisLanguage.equals("en_US"))
	{
		isUserLanguageEnglish=false;
	}
	//EgMappingInfo mappingInfo = new EgMappingInfo(thisLanguage);
	EgDateInfo dateInfo=new EgDateInfo();
	EgMaintenanceInfo egM=new EgMaintenanceInfo("manager");
	EgMaintenanceUtility maintenanceUtil=new EgMaintenanceUtility();
	EgTopoInfo topoInfo=new EgTopoInfo("manager");
	//IniFile uiIni = new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_ui.ini");
	int compNameLength = 18;
	int compHeadLength = 16;
	json = new JSONObject();

	labelObject.put("backButtonText",mappingInfo.getTextDescription("monitor.common.Back"));
	labelObject.put("searchDefaultText",mappingInfo.getTextDescription("monitor.common.Search"));
	labelObject.put("searchResultText",mappingInfo.getTextDescription("monitor.global.Search Results For "));
	labelObject.put("ListTitle",mappingInfo.getTextDescription("monitor.common.SEGMENTS"));
	//if ((d!=null) && (!d.equals("")))
	//{
	if(d.searchString!=null)
	{
		d.searchString =  egurkha.EgUIUtils.decodeSecurityChar(d.searchString);
	}
	if((totSegments!=0)||(d!=null && d.searchString!=null&&totSegments==0))
	{
		labelObject.put("ListName",mappingInfo.getTextDescription("monitor.segments.Segment Name"));
		labelObject.put("AssociatedSegments",mappingInfo.getTextDescription("monitor.common.Associated Elements"));

		json.put("showAssociations",new Boolean(r.showAssociations));
		if(r.showAssociations&&totSegments!=0)
		{
			labelObject.put("searchText",d.searchString);
			labelObject.put("Associations",mappingInfo.getTextDescription("monitor.common.Associations"));
		}
		json.put("showSearch",new Boolean(r.showSearch));
		json.put("isPartOf",new Boolean(d.partOf));
		if(r.showSearch)
		{
			if(d.from!=null&&d.from.equalsIgnoreCase("ZoneDashboard")||(d.partOf!=null&&d.partOf.equalsIgnoreCase("zone")))
			{

			}
			if(d.userName!=null)
			{

			}
			json.put("searchString",(d.searchString == null || d.searchString.length()<1)? "Search" :d.searchString);
		}
		else
		{

		}

		if (totSegments==0)
		{
			json.put("SearchNoListFound","true");
			json.put("SearchNoListFoundText",mappingInfo.getTextDescription("monitor.segmentDashboard.No segments found for the current search"));
		}
		if(abnormalSegmentCount!=0)
		{
			if(d.from!=null && d.from.equals("ZoneDashboard") && d.action.equals("segment"))
			{
				json.put("segmentForZone",d.zoneName);
				labelObject.put("zoneSegment",mappingInfo.getTextDescription("monitor.segments.Segments for the Zone "));
			}
			if(d.action.equalsIgnoreCase("segmentState"))
			{
				labelObject.put("segmentIn",mappingInfo.getTextDescription("monitor.segments.Segments in"));
				if(d.from.equalsIgnoreCase("ZoneDashboard"))
				{
					labelObject.put("forZone",mappingInfo.getTextDescription("monitor.segments.for the Zone")+" : " + d.zoneName);
				}
				if(d.userName!=null)
				{
					labelObject.put("forUser",mappingInfo.getTextDescription("monitor.common.For the User")+" : " + d.userName);
				}
				else
				{

				}
			}
			else
			{ 
				if(d.userName!=null)
				{
					labelObject.put("segmentForUser",mappingInfo.getTextDescription("monitor.servers.Segments for the User")+" : " + d.userName);
				}
			}

			int i = 0;
			int j = 0;
			EgSegment segment = null;

			rootItem = new JSONArray();
			for(i = 0; i < r.segmentList.size(); i++)//segment loop start here
			{
				JSONObject segmentItem = new JSONObject();
				segment = (EgSegment) r.segmentList.get(i);
				segmentItem.put("NameText",segment.getName());
				segmentItem.put("Tooltip",segment.getName());
				String segmentUrl = "/final/monitor/segmentDashboard.jsp?treeFlag="+treeFlag+"&outsideSegment=true&titleText=segment&selectNode=Segment$cap$"+EgURLEncoder.encode(segment.getName(),"UTF-8")+"&segmentFromZone="+EgURLEncoder.encode(segment.getName(),"UTF-8");

				segmentItem.put("URL",segmentUrl);
				segmentItem.put("StateName",segment.getState().getName());
				segmentItem.put("ifshowImage",ifshowImage);
				request.setAttribute("jsonObject",segmentItem);
				request.setAttribute("category","segment");
				request.setAttribute("itemName",segment.getName());

				%>
					<%@ include file="aggregateTabHandler.jsp" %>
				<%
				if(ifshowImage)
				{
					segment_image=(String)topoInfo.getValue("SEGMENT_DISPLAY_IMAGE",segment.getName());
					if(segment_image.indexOf("Small")!=-1)
					{
						segment_image=segment_image.replace("Small","48");
						if(segment_image.equals("serviceOthers48"))
						{
							segment_image="segment_GRAY";
						}
						segmentItem.put("SegmentImage",segment_image);
						segmentItem.put("StateName",segment.getState().getName());
					}
				}

				if (segment.getName().length() > compHeadLength)
				{
					//if length of the service name larger means come here and remove it
				}
				else
				{

				}

				EgComponentList componentList = segment.getComponentList();
				EgComponent component = null;
				int count = componentList.size();
				if(componentList != null && count>0)
				{
					int goodCount = componentList.getCount(State.getState("Good"));
					//count = count - goodCount;
					int compSize = count;

					labelObject.put("Components",mappingInfo.getTextDescription("monitor.common.Components"));

					innerItem = new JSONArray();
					JSONObject componentItem = new JSONObject();
					if(componentList != null)
					{
						componentItem.put("NameText",mappingInfo.getTextDescription("monitor.common.Components"));
						JSONArray componentInnetItem = new JSONArray();;
						for(j = 0; (j < compSize && j < r.dispCompCount); j++)
						{
							JSONObject componentObject = new JSONObject();
							EgSegment seg = null;
							if(j < compSize)
							{
								component = (EgComponent) componentList.get(j);
								if(component.getState().equals(State.GOOD))
								{
								// We show only abnormal components
								}
							}

							if ( j <compSize)
							{
								String site = "NULL";
								//boolean isSite = false;
								//this block for maintanence image
									String serverName = component.getName();
									componentObject.put("StateName","state_"+component.getState());
									String sid = "";
									String sname = "";
									String portno = "";
									String componentUrl = "";
									if (serverName != null && !serverName.equals(""))
									{
										StringTokenizer  tok=new StringTokenizer(serverName,":");  
										int tokens = tok.countTokens();
										sname = tok.nextToken();
										portno = tok.nextToken();
										if(portno.equalsIgnoreCase("NULL"))
										{
											serverName = sname;
										}
										if (tokens == 3)
											sid = tok.nextToken();
									}
									componentObject.put("NameText",serverName);
									componentObject.put("Tooltip",serverName);
									String currdate = dateInfo.egetDate(false);
									boolean  isHostMaintenance=egM.isItMaintenanceTime(currdate,sname,"","",true);
									boolean  isComponentMaintenance=egM.isItMaintenanceTime(currdate,sname,portno,sid,true);
									List  maintenaceTimePeriod=new ArrayList();
									List temp=null;
									if(isHostMaintenance)
									{
										temp=egM.getMaintenancePeriods(sname,"","",true);
										if(temp!=null && temp.size()>0)
											maintenaceTimePeriod.addAll(temp);
										temp=egM.getUnplannedMaintenancePeriods(sname,"","",true);
										if(temp!=null && temp.size()>0)
											maintenaceTimePeriod.addAll(temp);
									}
									if(isComponentMaintenance)
									{
										temp=egM.getMaintenancePeriods(sname,portno,sid,true);
										if(temp!=null && temp.size()>0)
										{
											maintenaceTimePeriod.addAll(temp);
										}
										temp=egM.getUnplannedMaintenancePeriods(sname,portno,sid,true);
										if(temp!=null && temp.size()>0)
											maintenaceTimePeriod.addAll(temp);
									}
									int noOfLines=maintenaceTimePeriod.size();
									String maintenaceTimePeriodStr=maintenanceUtil.convertMaintenacevectorToString(maintenaceTimePeriod,user);
									//maintanence block end here
									
									if(r.displayCompType)
									{
										String displayComponentType = mappingInfo.getComponentTypeDescription(component.getType());
										componentUrl = "../servlet/com.eg.EgMonitorController?site="+EgURLEncoder.encode(site,"UTF-8")+"&monCmd=componentList&from=MainDashboard&action=componentType&componentType="+EgURLEncoder.encode(component.getType(),"UTF-8")+"&searchIndComps=true&segment="+EgURLEncoder.encode(segment.getName(),"UTF-8");
										componentObject.put("NameText",displayComponentType);
										
									}
									else
									{
										componentUrl = "../servlet/com.eg.EgDashboardController?from=list&site="+EgURLEncoder.encode(site,"UTF-8")+"&qctr=0&comptype="+EgURLEncoder.encode(component.getType(),"UTF-8")+"&host="+EgURLEncoder.encode(component.getName(),"UTF-8")+"&tab=LayerModel&toDashBoardLayer=true&treeFlag="+treeFlag+"&action=segment";
										if(isHostMaintenance || isComponentMaintenance)
										{
											componentObject.put("MaintenanceTime",maintenaceTimePeriodStr);
											componentObject.put("NoOfLines",String.valueOf(noOfLines));
										}
									}
									componentObject.put("URL",componentUrl);
								
							}
							componentInnetItem.add(componentObject);
						}
						componentItem.put("InnerItems",componentInnetItem);
					}
					innerItem.add(componentItem);
					
					segmentItem.put("InnerItems",innerItem);
				}
				rootItem.add(segmentItem);
			}
			json.put("RootItem",rootItem);
		}

		if(normalSegmentCount!=0)
		{
			if(!(d.action.equalsIgnoreCase("segmentState") && !d.state.equals(State.GOOD)))
			{
				labelObject.put("NormalSegments",mappingInfo.getTextDescription("monitor.segments.Normal Segments"));
				if (normalSegmentCount!=0)
				{
					r.segmentList = r.segmentList.search(State.GOOD);
					int count = r.segmentList.size();

					if (count <= 9)
					{
						count = 9;
					}
					else  if(count % 3 > 0)
					{
						count = count + 3 - count % 3;
					}

					int i = 0;
					EgSegment segment = null;
					for(i = 0; i < r.segmentList.size() || i < count; i++)
					{
						boolean isSite = false;
						if(i < r.segmentList.size())
						{
							segment = (EgSegment) r.segmentList.get(i);
						}
						if ( i <r.segmentList.size())
						{
							if (segment.getName().length() > compNameLength)
							{

							}
							else
							{

							}
						}
					}
				}
			}
		}
	}
	//}
	else
	{
		json.put("NoListFound","true");
		json.put("NoListFoundText",mappingInfo.getTextDescription("monitor.segments.No segments found"));
	}
	if ((d!=null) && (!d.equals("")))
	{
     if(d.action!=null && d.action.equalsIgnoreCase("globalsearch") || d.action.equalsIgnoreCase("globalsearchallsegment") )
     {
      /* if(request.getQueryString()!=null)
      {
	  	 session.setAttribute("globalSearchLastSessionURL","/final/monitor/segmentDashboard.jsp?"+request.getQueryString());
				
      }
      else
      {
	    	session.setAttribute("globalSearchLastSessionURL","/final/monitor/segmentDashboard.jsp");
      } */
	  if(d.searchString!=null && d.searchString.length()>0)
		{
			session.setAttribute("monitorLastSession","/final/servlet/com.eg.EgMonitorController?monCmd=segmentList&from=segmentList&action=globalsearch&searchString="+d.searchString+"&treeOpen=false&isFromMenu=false&refresh=true");
			
		}
		else
		{
			session.setAttribute("monitorLastSession","/final/monitor/segmentDashboard.jsp?");
		}
    }
    else
    {  
     	if(request.getQueryString()!=null)
	    {
		   session.setAttribute("monitorLastSession","/final/monitor/segmentDashboard.jsp?"+request.getQueryString());
	    }
	    else
	    {
		   session.setAttribute("monitorLastSession","/final/monitor/segmentDashboard.jsp?");
	    }
    }
	}
	json.put("screenLabels",labelObject);
	response.getWriter().write(json.toString());
}
catch(Exception e)
{
	System.out.println("Exception is segmentList page "+e);
	e.printStackTrace();
}
%>