<%@ include file = "../../../admin/EgTrackerAJSON.jsp" %>
<%@ page import = "java.io.*"%>
<%@ page import = "java.util.*" %>
<%@ page import = "java.text.SimpleDateFormat" %>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.AgentConfig"%>
<%@ page import = "com.eg.EgExternalInfo"%>
<%@ page import = "com.egurkha.util.StringUtils"%>
<%@ page import="javax.xml.transform.dom.DOMSource"%>
<%@ page import ="javax.xml.parsers.DocumentBuilder"%>
<%@ page import ="javax.xml.parsers.DocumentBuilderFactory"%>
<%@ page import ="javax.xml.soap.MessageFactory"%>
<%@ page import ="org.w3c.dom.Document"%>
<%@ page import ="org.w3c.dom.Element"%>
<%@ page import ="org.xml.sax.InputSource"%>
<%@ page import ="org.w3c.dom.NodeList"%>
<%@ page import ="org.w3c.dom.Node"%>
<%@ page import = "net.sf.json.*" %>
<%@ page import="java.io.File"%>

<%@ page import="egurkha.UserBean"%>
<%@ page import="com.eg.EgServerList"%>
<%@ page import="com.eg.EgLicenseInfo" %>
<%@ page import = "java.net.*"%>
<%@ page language="java" contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<%
	response.setHeader("Cache-Control","no-store");
	response.setHeader("Pragma","no-cache");
	response.setDateHeader("Expires", -1);
%>

<%
	JSONObject rootJson = new JSONObject();
	JSONObject agentJson = new JSONObject();
	try
	{	
		String appType = request.getParameter("appType");
		String latestAgentVersion = "",latestManagerVersion = "";
		String configDir = EgInstallInfo.getInstallDir()+"/manager/config/";
		String managerVersion = EgInstallInfo.version;
		IniFile dbIni = new IniFile(configDir+"eg_db.ini");
		IniFile servicesIni = new IniFile(configDir+"eg_services.ini");
		String managerUrl = dbIni.getValue("DB_PROPERTIES","ManagerUrl");
		String checkForUpdateURL = servicesIni.getValue("eG_Utilities","CheckForUpdateURL");
		String managerIP = managerUrl.substring(managerUrl.indexOf("//")+2,managerUrl.lastIndexOf(":"));
		File fXmlFile = new File(configDir+"AgentConfig.xml");
		String fileName = "";
		String jsonText = "",inputLine = "",actionParam ="";
		if(appType!=null && appType.equalsIgnoreCase("checkforupdates"))
		{
			actionParam = "versionupdates";
		}
		else{
			actionParam = "helpcenterupdates";
		}
		if(checkForUpdateURL !=null && checkForUpdateURL.length() > 0)
		{
			URL url = new URL(checkForUpdateURL+"?action="+actionParam);
					
			URLConnection conn = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			while ((inputLine = in.readLine()) != null) {
				System.out.println(inputLine);
				jsonText=inputLine;
			}
			jsonText= jsonText.substring(jsonText.indexOf("(")+1,jsonText.lastIndexOf(")"));
			System.out.println("File Content: \n" + jsonText);	
			
			JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonText); 
			if(appType!=null && appType.equalsIgnoreCase("checkforupdates"))
			{
				latestManagerVersion = (String)obj.get("latestManagerVersion");
				latestAgentVersion = (String)obj.get("latestAgentVersion");

				rootJson.put("latestManagerVersion", latestManagerVersion);
				rootJson.put("latestAgentVersion", latestAgentVersion);
				rootJson.put("NewFeaturesLink", (String)obj.get("NewFeaturesLink"));

				if ( fXmlFile.exists() ){
					DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
					DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
					Document doc = dBuilder.parse(fXmlFile);
					doc.getDocumentElement().normalize();

					NodeList nList = doc.getElementsByTagName("Agent");
					EgLicenseInfo licInfo = new EgLicenseInfo();
					ArrayList allAgents=licInfo.getExternalAgents();
					JSONArray agentList=new JSONArray();
					ArrayList notUpdatedList=new ArrayList();
					String basicAgentVersion="",basicAgentProcType="";
					String loginUserDateTime ="", hourForDisplay ="", minForDisplay ="";
					AgentConfig agentConfig = AgentConfig.getAgentConfig();
					String ids[] = 	agentConfig.getArrayOfAgentIDs();
					EgLicenseInfo licenseInfo = new EgLicenseInfo();
					ArrayList listOfExternalAgents = licenseInfo.getExternalAgents();
					ArrayList listOfRemoteAgents = licenseInfo.getRemoteAgents();
					Vector agentListWithStatus = agentConfig.getUpgradeStatusForAllAgents();
					EgExternalInfo egExternalInfo = new EgExternalInfo("manager");
					if(nList!=null){
						for (int temp = 0; temp < nList.getLength(); temp++) {
							String tmpAgent="";
							Node nNode = nList.item(temp);
							System.out.println("\nCurrent Element :" + nNode.getNodeName());
							if (nNode.getNodeType() == Node.ELEMENT_NODE) {
								Element eElement = (Element) nNode;
								String agentID = eElement.getAttribute("ID");
								String getAgentName = "";
								
							//	if(agentID.indexOf(managerIP)>-1){
									basicAgentVersion=eElement.getElementsByTagName("Version").item(0).getTextContent();
									basicAgentProcType=eElement.getElementsByTagName("ProcType").item(0).getTextContent();
									String[] arrOptions = agentID.split(":");
									for(int i =0; i < arrOptions.length ; i++){
										String agentName=arrOptions[i];
										if(listOfExternalAgents.contains(agentName)|| listOfRemoteAgents.contains(agentName))
										{
											getAgentName=agentName;
										}
									}
									if(getAgentName.length()>0){
										tmpAgent = getAgentName;	
									}
									else{
										String hostName=eElement.getElementsByTagName("HostName").item(0).getTextContent();
										tmpAgent = hostName;
									 }
									String version=eElement.getElementsByTagName("Version").item(0).getTextContent();
									String agentVersion=version.replaceAll("\\.","");
									String lAgentVersion=latestAgentVersion.replaceAll("\\.","");
									int agtVersion = Integer.parseInt(agentVersion);
									int lagtVersion = Integer.parseInt(lAgentVersion);
									if(agtVersion<lagtVersion){
										notUpdatedList.add(tmpAgent);
									}
							//	}
							}
						}
						rootJson.put("totalAgentsCount",nList.getLength());
						rootJson.put("NotUpdatedAgentsCount",notUpdatedList.size());
						rootJson.put("basicAgentVersion",basicAgentVersion);
						rootJson.put("basicAgentProcType",basicAgentProcType);
					}
					String mVersion=managerVersion.replaceAll("\\.","");
					String lmVersion=latestManagerVersion.replaceAll("\\.","");
					int mgrVersion = Integer.parseInt(mVersion);
					int lmgrVersion = Integer.parseInt(lmVersion);
					if(mgrVersion<lmgrVersion){
						rootJson.put("isManagerUpdated","false");
					}
					else{
						rootJson.put("isManagerUpdated","true");
					}
				}
			}
			else{
				rootJson.put("helpCenterURL",(String)obj.get("helpCenterURL"));
			}
			rootJson.put("success","true");
		}
		else{
			rootJson.put("ErrMsgsJson", "Check for updates URL not configured, please check with the settings.");
		}
		
	}
	catch ( Exception e )
	{		
		String errMsg = e.getMessage();
		if(errMsg != null){
			rootJson.put("ErrMsgsJson", "Could not able to reach server, please check with the settings.");
		}
	}
	response.setContentType("text/html;charset=UTF-8");
	response.getWriter().write(rootJson.toString());
%>

