<%@ page import = "egurkha.EgDbAdapterUI"%>
<%@ page import = "com.eg.EgDbAdapterTypeUI"%>
<%@ page import = "com.egurkha.monitor.alarms.*"%>
<%@ page import = "java.net.*" %>
<%@ page import = "javax.net.ssl.*" %>
<%@ page import = "java.io.*" %>
<%@ page import = "java.sql.*"%>
<%@ page import = "java.util.*"%>
<%@ page import = "java.text.SimpleDateFormat" %>
<%@ page import = "com.egurkha.*"%>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "com.eg.EgAlarmTable"%>
<%@ page import = "egurkha.reporter.ErUserData"%>
<%@ page import="net.sf.json.JSONObject"%>
<%@ page import="net.sf.json.JSONArray"%>
<%@ page import = "com.eg.EgInstallInfo"%>
<%@ page import = "com.eg.IniFile"%>
<%@ page import = "com.eg.EgCrypt"%>
<%@ page import = "com.egurkha.admin.mfa.GoogleAuthenticator"%>

<%@ taglib prefix = "egui" uri = "../WEB-INF/eg-taglib.tld"%>
<%@ page language="java" contentType="application/json;charset=UTF-8" pageEncoding="UTF-8" %>

<%!
	String hostName[] ={"https://egontap.eginnovations.com","http://forums.eginnovations.com","https://trials.eginnovations.com","https://customer.eginnovations.com/egcrm/","http://egcs11.eginnovations.com"};
	String arr[]={"normal","high"};
	String userArray[] = {"bob","kim","mike","tom","jim","tim","jeff","sam","ken","keith","julie","mark","adam"};	
	String userDescArray[] = {"bobdesc some details may come","kimdesc some details may come","mikedesc some details may come","tomdesc some details may come","jimdesc some details may come","timdesc some details may come","jeffdesc some details may come","samdesc some details may come","kendesc some details may come","keithdesc some details may come","juliedesc some details may come","markdesc some details may come","adamdesc some details may come"};
%>

<%	long start = System.currentTimeMillis();
	response.setContentType("application/json");
    response.setHeader("Cache-Control","no-store");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader("Expires", -1);
	int alerts = 0;	
	int unknowns = 0;
	
	String p_status = "";
	String count = "1";
	String status = null;
	String  callback=request.getParameter("callback");
	String  isPortal=request.getParameter("isPortal");
	boolean isPortalstaus=false;

	JSONObject demo_Statusinnerobj=new JSONObject();
	JSONObject rootJson=new JSONObject();
	JSONArray demo_Status=new JSONArray();
	JSONArray portal_Status=new JSONArray();
	JSONArray demo_Statusinner=new JSONArray();
	ArrayList user_list = new ArrayList();
	Hashtable user_server = new Hashtable();	

	HashMap userQuery = new HashMap();
	HashMap portalStatus = new HashMap();
	HashMap errorMsg = new HashMap();
	HashMap mapAlarmCount = new HashMap();

	mapAlarmCount.put("bob","c1,mj1,mr2"); //("name","critical,major,minor")
	mapAlarmCount.put("kim","c1,mj2,mr2");
	mapAlarmCount.put("mike","c1,mj2,mr2");
	mapAlarmCount.put("tom","c1,mj2,mr2");
	mapAlarmCount.put("sam","c1,mj2,mr2");
	mapAlarmCount.put("ken","c1,mj2,mr2");
	mapAlarmCount.put("jim","c1,mj1,mr2");
	mapAlarmCount.put("jeff","c1,mj1,mr2");
	mapAlarmCount.put("julie","c1,mj2,mr1");
	mapAlarmCount.put("tim","c1,mj1,mr1");
	mapAlarmCount.put("keith","c1,mj1,mr0");
	mapAlarmCount.put("mark","c1,mj1,mr2");
	mapAlarmCount.put("adam","c1,mj2,mr2");
	if(isPortal!=null && isPortal.equals("yes"))
	{
		isPortalstaus=true;
	}
	// To get list of user from DB 

	

	try
	{
		if (userArray!=null && userArray.length>0)
		{
		
			for(int i=0; i<userArray.length; i++)	// to get servers for each user 
			{
				String uname = userArray[i];
				user_list.add(uname);
				//out.println("uname ----- "+uname);
				ErUserData userData = new ErUserData(uname,true);
				User user =userData.getUser(uname);
				List server_list = new ArrayList();
				server_list = user.getServers(false);
				//out.println(" server list = " + server_list);
				List queryList = new ArrayList();
				String q_alarm = "select PRIORITY,count(*) from alarm where (comp_name like ";
				String strComponent = "";
				for(int j =0; j< server_list.size(); j++)
				{		
					String comp_name = (String) server_list.get(j);
					if(comp_name!=null && comp_name.indexOf(":")>-1)
					{
						comp_name = comp_name.substring(comp_name.indexOf(":")+1);
						if (comp_name.indexOf(":")>-1)
							comp_name=comp_name.substring(0,comp_name.indexOf(":"));
						comp_name = "'%" + comp_name + ":%'" + " OR comp_name like ";
					}

					/*if ( j == server_list.size()-1)
						strComponent = strComponent + "'"+comp_name+"')";
					else 
						strComponent = strComponent+"'"+comp_name+"',";*/

					strComponent = strComponent + comp_name;
				}
				if (strComponent.endsWith(" OR comp_name like "))
					strComponent = strComponent + "'')";

				q_alarm = q_alarm+strComponent + " group by PRIORITY" ;				
				queryList.add(q_alarm);
				//out.println("q_alarm --- "+q_alarm);

				String q_unknowns = "select count(*) u_count from report where STATE='UNKNOWN' and (comp_name like ";
				q_unknowns = q_unknowns+strComponent;

				queryList.add(q_unknowns);
				//out.println("archana : q_unknowns ________"+q_unknowns);				
				userQuery.put(uname,queryList);
			}
		}
		
	}catch(Exception e)
	{
		System.out.println("Exception in user db -- "+e);
		e.printStackTrace();
	}
//----------- DB connection - user - server list ends ----------------

//----------- DB connection - alarm & count begins ----------------
	
	ArrayList arryList = new ArrayList();
	
	EgDbAdapterUI egDb = EgDbAdapterTypeUI.getObject();
	status = egDb.setConnection();
	ResultSet rs = null;

	try
	{
		if (status != null && status.equals("CONNECTED"))
		{			
			for(int i=0; i < user_list.size(); i++)
			{
				String name1 = (String) user_list.get(i);
				arryList = (ArrayList) userQuery.get(name1);

				String alertQuery = (String) arryList.get(0);
				String unknownQuery = (String) arryList.get(1);
				
				try
				{
					rs = egDb.dbselect(unknownQuery);

					// for unknownQuery
					if(rs != null)
					{
						rs.next();
						unknowns = rs.getInt(1);
					}
				}
				catch (Exception er)
				{
				}
				finally
				{
					try
					{
						if(rs!=null)
						{
							rs.close();
							rs = null;
						}
					}
					catch (Exception eer)
					{
					}
				}
				
				// for alertQuery
				
				int minor = 0;
				int major = 0;
				int critical = 0;
				
				try
				{
					rs = egDb.dbselect(alertQuery);
					if(rs != null)
					{
						while(rs.next())
						{	
							String priority = rs.getString(1);
							alerts = rs.getInt(2);

							if(priority.equalsIgnoreCase("LOW"))
								minor += alerts;
							else if(priority.equalsIgnoreCase("INTERMEDIATE"))
								major += alerts;
							else if(priority.equalsIgnoreCase("HIGH"))
								critical += alerts;

						}
					}
				}
				catch (Exception er)
				{
				}
				finally
				{
					try
					{
						if(rs!=null)
						{
							rs.close();
							rs = null;
						}
					}catch(Exception ee){}
				}
				
				String defaultAlert = (String) mapAlarmCount.get(name1);

				int criticalD = Integer.parseInt(defaultAlert.substring(defaultAlert.indexOf("c")+1,defaultAlert.indexOf("c")+2));

				int majorD = Integer.parseInt(defaultAlert.substring(defaultAlert.indexOf("mj")+2,defaultAlert.indexOf("mj")+3));

				int minorD = Integer.parseInt(defaultAlert.substring(defaultAlert.indexOf("mr")+2,defaultAlert.indexOf("mr")+3));
		
				String msg="";

				if(critical >= criticalD && major >= majorD && minor >= minorD && unknowns == 0)
				{
					count = "0"; //tick
					msg = "-";
				}
				else
				{
					count = "1"; //wrong
				}
				
				if(critical < criticalD || major < majorD || minor < minorD)
					msg = "Alerts";
				if(unknowns > 0)
					msg = "Unknowns";					
				
				errorMsg.put(name1,msg);
				msg = "";

				user_server.put(name1,count);
				count = "1";
				
			}
		}
	}catch(Exception e)
	{
		System.out.println("Exception in user db -- "+e);
		e.printStackTrace();
	}
	finally
	{
		 egDb.releaseConnection(true);
	}
	EgDbAdapterTypeUI.releaseObject(egDb); 

//----------- DB connection - alarm & count - ends ----------------

	// Current Date and Time
	
	SimpleDateFormat sdf_date = new SimpleDateFormat("MMMM, dd  yyyy");
	SimpleDateFormat sdf_time = new SimpleDateFormat(" HH:mm:ss z");  
	java.util.Date today = new java.util.Date();
	String date = sdf_date.format(today);
	String time = sdf_time.format(today);
	JSONObject dateTime_obj = new JSONObject();
	dateTime_obj.put("date",date);	
	dateTime_obj.put("time",time);
	demo_Status.add(dateTime_obj);
	
//*****************DemoStatus***************

	int c =0;
	IniFile specsIni =  new IniFile(EgInstallInfo.getInstallDir() + "/manager/config/eg_specs.ini");
	String accessKey = specsIni.getValue("SETTINGS","EG_SERVER");
	accessKey = EgCrypt.encrypt(accessKey);

	String sessionId = session.getId();
	sessionId = EgCrypt.encrypt(sessionId);

	String secretKey = GoogleAuthenticator.getRandomSecretKey();
	String kpe = EgCrypt.encrypt(secretKey);
	
	java.util.Date currDate = new java.util.Date();
	String userDateTimeFormat = "MM/dd/yyyy HH:mm:ss";
	SimpleDateFormat sdf = new SimpleDateFormat(userDateTimeFormat);
	String userDate = sdf.format(currDate); 
	String dpe = EgCrypt.encrypt(userDate);

	String randomNumber = GoogleAuthenticator.getTOTPCode(secretKey, userDate);
	String rpe = EgCrypt.encrypt(randomNumber);

	for(int i = 0; i < user_list.size(); i++)
	{
		JSONObject details_obj = new JSONObject();
		String name = (String) user_list.get(i);
		String nameDemo = name+"demo";
		String message="";
		details_obj.put("name",name.toUpperCase());
		if(user_server.get(name) != null)
		{				
			c = Integer.parseInt((String)user_server.get(name));				
		}
		if( c < 2)
		{
			String demo_url="http://demo.eginnovations.com/final/servlet/com.egurkha.EgNewLoginServlet?uname="+name+"&upass="+name+"demo&ape="+accessKey+"&spe="+sessionId+"&kpe="+kpe+"&dpe="+dpe+"&rpe="+rpe;
			details_obj.put("status",arr[c]);
			details_obj.put("url",demo_url);	
			details_obj.put("desc",userDescArray[i]);
		}
		if(errorMsg.get(name) != null)
		{
			message = (String) errorMsg.get(name);	
			details_obj.put("message",message);	
		}
		demo_Status.add(details_obj);
	}			
	rootJson.put("demostatus",demo_Status);

//*****************PortalStatus***************
if(!isPortalstaus)
{
	for(int k=0; k< hostName.length; k++)
	{
		String hostname = hostName[k];
		URL hosturl = null;
		HttpsURLConnection  https_con = null;
		HttpURLConnection  http_con = null;
		boolean resp_status = false;
		try
		{			
			if(hostname.startsWith("https"))
			{
				//hosturl = new URL(null,hostname,new sun.net.www.protocol.https.Handler());
				hosturl = new URL(hostname);
				https_con = (HttpsURLConnection) hosturl.openConnection();
				https_con.setConnectTimeout(10*1000);
				int resp_code = https_con.getResponseCode();
				resp_status = https_con.getFollowRedirects();
				if(resp_status && (resp_code == 200))
					p_status = "0";
				else
					p_status = "1";
			}
			else if(hostname.startsWith("http"))
			{
				hosturl = new URL(hostname);
				http_con = (HttpURLConnection) hosturl.openConnection();
				http_con.setConnectTimeout(10*1000);
				http_con.setReadTimeout(10*1000);
				int resp_code = http_con.getResponseCode();
				resp_status = http_con.getFollowRedirects();
				if(resp_status || (resp_code == 200))
					p_status = "0";
				else
					p_status = "1";
			}
		}catch(Exception e)
		{
			p_status = "1";
			System.out.println("Exception.."+e+" p_status--"+p_status+"..........");
			e.printStackTrace();
		}
		portalStatus.put(hostname,p_status);
	}	
	for(int i = 0; i< hostName.length; i++)						
	{
		JSONObject portdetails_obj = new JSONObject();
		String name = hostName[i];
		String hName = hostName[i];
		hName = hName.substring(hName.indexOf("//")+2,hName.indexOf("."));
		int s = Integer.parseInt((String) portalStatus.get(name));
		portdetails_obj.put("name",hName.toUpperCase());
		portdetails_obj.put("status",arr[s]);
		portdetails_obj.put("url",name);
		portal_Status.add(portdetails_obj);
	}
	rootJson.put("portalstatus",portal_Status);
	String resp=callback+"("+rootJson.toString()+")";
	out.println(resp);
}else
{
	//String resp=callback+"("+rootJson.toString()+")";
	out.println(rootJson.toString());
}
%>
	