/*
 * 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.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;

import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import rbsla.environment.ECAConstraints;

public class ActThread extends Thread
{
	
	private StatsActual statsActual;
	
	private TimeSeriesCollection dataset;
	private Vector checked;
	private Vector oldChecked;
	private Connection con;
	private int counter;
	
	public ActThread(StatsActual stats)
	{
		statsActual = stats;
		dataset = stats.getDataset();
		checked = stats.getChecked();
		oldChecked = stats.getChecked();
		counter = 0;
		
	}
	
	public void run()
	{
		try
		{
			Class.forName(ECAConstraints._DB_DRIVER);
			con = DriverManager.getConnection(ECAConstraints._DB_NAME, ECAConstraints._DB_USER, ECAConstraints._DB_PWD);
			Statement st = con.createStatement();
			while(true)
			{
				sleep(1000);
				
				Millisecond now = new Millisecond();
				int tmpIndex = counter % 5;
				counter++;
				
				//hier update
				checked = statsActual.getChecked();
				int ch = checked.size();
				
				if(tmpIndex < ch)
				{
					String srv = (String)checked.get(tmpIndex);
					
					String q = "SELECT Stat FROM availability WHERE Host='" + srv + "' ORDER BY Time DESC";
					ResultSet rs = st.executeQuery(q);
					int aval = 0;
					if(rs.last())
					{
						aval = Math.abs(100*rs.getInt("Stat") - 2*tmpIndex);
					}
					
					TimeSeries ser = dataset.getSeries(tmpIndex);
					ser.add(now, aval);
				}
			
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}
