
/*
 * Copyright (C) 1999-2006 <a href="mailto:adrian.paschke@gmx.de">Adrian Paschke</a>
 * 
 * The RBSLM Environment is part of the Rule Based Service Level Agreement (RBSLA)
 * framework, available at 
 * <a href=" http://ibis.in.tum.de/staff/paschke/rbsla/index.htm">RBSLA</a>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package rbsla.environment.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Time;
import java.util.GregorianCalendar;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;

import rbsla.environment.ECAConstraints;
import rbsla.environment.view.SpringUtilities;

public class StatsAvalaibility extends JFrame implements ActionListener
{	
	//propertyies
	private JPanel northPanel;
	//stats
	private JPanel centerPanel;
	//buttonpanel
	private JPanel southPanel;
	
	//property fields
	private JTextField host;
	private JComboBox dateFrom;
	private JComboBox dateTo;
	
	//jlabels for statistic window
	private JLabel srvLabel;
	private JLabel avalLabel;
	private JLabel rtdLabel;
	private JLabel ttrLabel;
	private JLabel avalOLabel;
	private JLabel rtdOLabel;
	
	
	//buttons
	private JButton close;
	private JButton refresh;
	
	public StatsAvalaibility()
	{
		super("Static Stats");
		this.getContentPane().setLayout(new BorderLayout());
		
		//initialize the panels
		northPanel = new JPanel();
		centerPanel = new JPanel();
		southPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		
		//set the panels
		this.add(northPanel, BorderLayout.NORTH);
		this.add(centerPanel, BorderLayout.CENTER);
		this.add(southPanel, BorderLayout.SOUTH);
		
		//configure north panel
		host = new JTextField();
		dateFrom = new JComboBox(ECAConstraints._PERIOD);
		dateTo = new JComboBox(ECAConstraints._PERIOD);
		
		JLabel hostTmp = new JLabel("Server Address:",SwingConstants.RIGHT);
		JLabel dFromTmp = new JLabel("From:",SwingConstants.RIGHT);
		JLabel dToTmp = new JLabel("To:",SwingConstants.RIGHT);
		
		hostTmp.setPreferredSize(new Dimension(95, 20));
		dFromTmp.setPreferredSize(new Dimension(95, 20));
		dToTmp.setPreferredSize(new Dimension(95, 20));
		
		SpringLayout nLayout = new SpringLayout();
		northPanel.setLayout(nLayout);
		
		northPanel.add(hostTmp);
		northPanel.add(host);
		northPanel.add(new JLabel());
		northPanel.add(new JLabel());
				
		northPanel.add(dFromTmp);
		northPanel.add(dateFrom);
		northPanel.add(dToTmp);
		northPanel.add(dateTo);
		
		SpringUtilities.makeCompactGrid(northPanel, 2, 4, 8, 8, 8, 8);
		
		//configure center panel
		
		SpringLayout cLayout = new SpringLayout();
		centerPanel.setLayout(cLayout);
		centerPanel.setBackground(new Color(220,220,220));
		
		srvLabel = new JLabel();
		avalLabel = new JLabel();
		rtdLabel = new JLabel();
		ttrLabel = new JLabel();
		avalOLabel = new JLabel();
		rtdOLabel = new JLabel();
		
		
		centerPanel.add(srvLabel);
		centerPanel.add(new JLabel("SLA"));
		centerPanel.add(new JLabel("Effective"));
		centerPanel.add(new JLabel("Overall"));
		
		centerPanel.add(new JLabel("Availability"));
		centerPanel.add(new JLabel("98%"));
		centerPanel.add(avalLabel);
		centerPanel.add(avalOLabel);
		
		centerPanel.add(new JLabel("RoundTripDelay"));
		centerPanel.add(new JLabel("40ms"));
		centerPanel.add(rtdLabel);
		centerPanel.add(rtdOLabel);
		
		centerPanel.add(new JLabel("TimeToRepair"));
		centerPanel.add(new JLabel("10h"));
		centerPanel.add(ttrLabel);
		centerPanel.add(new JLabel("N/A"));
		
		SpringUtilities.makeCompactGrid(centerPanel, 4, 4, 8, 8, 8, 8);
		
		//initialise buttons and add listeners
		close = new JButton(ECAConstraints._EXIT);
		refresh = new JButton(ECAConstraints._REFRESH);
		
		close.addActionListener(this);
		refresh.addActionListener(this);
		
		//set the buttons 
		southPanel.add(refresh);
		southPanel.add(close);
		
		
		this.setSize(new Dimension(600,300));
		this.setResizable(false);
		this.setVisible(true);
		
	}
	
	public void actionPerformed(ActionEvent e)
	{
		String cmd = e.getActionCommand();
		if(cmd.equals(ECAConstraints._EXIT))
		{
			this.dispose();
		}
		else if(cmd.equals(ECAConstraints._REFRESH))
		{			
			String ser = host.getText();
			String dFrom = (String)dateFrom.getSelectedItem();
			String dTo = (String)dateTo.getSelectedItem();
			
			String[] dFA = dFrom.split("/");
			String[] dTA = dTo.split("/");
			dFrom = dFA[1] + "-" + dFA[0] + "-" + "01";
			dTo = dTA[1] + "-" + dTA[0] + "-";
			if(dTA[0].equals("01") || dTA[0].equals("03") || dTA[0].equals("05")  || dTA[0].equals("07")  || dTA[0].equals("08")  || dTA[0].equals("10") || dTA[0].equals("11"))
				dTo += "31";
			else if(dTA[0].equals("04") || dTA[0].equals("06") || dTA[0].equals("09")  || dTA[0].equals("11"))
				dTo += "30";
			else if(dTA[0].equals("02"))
				dTo += "28";
			//connect to the database
			try
			{
				//standard values for the statistics
				float avgAval = -1;
				float avgRTD = -1;
				float avgRT = -1;
				float oAval = -1;
				float oRTD = -1;
				
				Class.forName(ECAConstraints._DB_DRIVER);
				Connection con = DriverManager.getConnection(ECAConstraints._DB_NAME, ECAConstraints._DB_USER, ECAConstraints._DB_PWD);
				Statement st = con.createStatement();
				
				//get the average availability
				String q = "SELECT AVG(stat) FROM availability a WHERE a.Host='"+ser+"' AND a.Time BETWEEN '"+dFrom+"' AND '"+dTo+"'";
				ResultSet rs = st.executeQuery(q);
				if(rs.next())
				{
					avgAval = rs.getFloat(1);
				}				
				
				//get the average round trip delay
				q = "SELECT AVG(value) FROM rtd r WHERE r.Host='"+ser+"' AND r.Time BETWEEN '"+dFrom+"' AND '"+dTo+"'";
				rs = st.executeQuery(q);
				if(rs.next())
				{
					avgRTD = rs.getFloat(1);
				}	
				
				//calculate the average time to rapair the damage
				q = "SELECT Host, Stat, Time FROM availability a WHERE a.Stat = 0 AND a.Host='"+ser+"' ORDER BY a.Time ASC";
				Statement st2 = con.createStatement();
				rs = st.executeQuery(q);
				long diffGes = 0;
				int counter = 0;
				while(rs.next())
				{
					Object ob = rs.getObject(3);
					String q2 = "SELECT Time FROM availability a WHERE a.Stat=1 AND a.Host='"+ser+"' AND a.Time > '"+ ob +"' ORDER BY a.Time ASC";
					ResultSet rs2 = st2.executeQuery(q2);
					if(rs2.next())
					{
						Date d1 = rs.getDate("Time");
						Date d2 = rs2.getDate("Time");
						Time t1 = rs.getTime("Time");
						Time t2 = rs2.getTime("Time");
						
						String[] d1F = d1.toString().split("-");
						int y1 = (new Integer(d1F[0])).intValue();
						int m1 = (new Integer(d1F[1])).intValue();
						int da1 = (new Integer(d1F[2])).intValue();
						
						String[] d2F = d2.toString().split("-");
						int y2 = (new Integer(d2F[0])).intValue();
						int m2 = (new Integer(d2F[1])).intValue();
						int da2 = (new Integer(d2F[2])).intValue();
						
						GregorianCalendar gCVon = new GregorianCalendar(y1, m1, da1, t1.getHours(), t1.getMinutes(), t1.getSeconds());
						GregorianCalendar gCBis = new GregorianCalendar(y2, m2, da2, t2.getHours(), t2.getMinutes(), t2.getSeconds());
					
						counter++;
						diffGes += gCBis.getTimeInMillis() - gCVon.getTimeInMillis();
						
					}
				}
				double avgDiff = 0.0;
				counter *= 60000;
				if(counter>0)
				{
					avgDiff =  (double)(diffGes) / (double)counter;
				}
				
				String avgTTR = avgDiff + "";
				int komma = avgTTR.indexOf(".");
				avgTTR = avgTTR.substring(0, komma+2);
				
				//overall values
				String q1 = "SELECT AVG(stat) FROM availability a WHERE a.Host='"+ser+"'";
				String q2 = "SELECT AVG(value) FROM rtd r WHERE r.Host='"+ser+"'"; 
				
				ResultSet res = st.executeQuery(q1);
				if(res.next())
				{
					oAval = res.getFloat(1);
				}
				
				res = st.executeQuery(q2);
				if(res.next())
				{
					oRTD = res.getFloat(1);
				}
				
				srvLabel.setText(ser);
				avalLabel.setText(avgAval + "%");
				avalOLabel.setText(oAval + "%");
				rtdLabel.setText(avgRTD + "ms");
				rtdOLabel.setText(oRTD + "ms");
				ttrLabel.setText(avgTTR + "min");
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
			
			
		}
	}
}
