package unileipzig.isys.neuronviz.kernel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Vector;

/**
 * Class DataStreamer
 * 
 */
abstract public class DataStreamer implements Runnable
{
	protected Vector listeners = new Vector();
	protected boolean receiveEnabled = true;
	protected boolean threadRunning = false;
	
	private BufferedReader dataReader = null;

	/**
	 * 
	 * @param listener
	 * @return
	 */
	public void addDataListener(DataListener listener)
	{
		listeners.add(listener);
	}

	/**
	 * 
	 * @param listener
	 * @return
	 */
	public void removeDataListener(DataListener listener)
	{
		listeners.remove(listener);
	}

	/**
	 * 
	 * @param event
	 * @return
	 */
	protected synchronized void notifyData(DataEvent event)
	{
		for (int i = 0; i < listeners.size(); i++)
		{
			((DataListener) (listeners.get(i))).dataReceived(event);
		}
	}

	public void run()
	{
		while (receiveEnabled)
		{
			threadRunning = true;
			// recieve data as long receiver is enabled
			try
			{
				if (dataReader.ready())
				{
					String s = dataReader.readLine();
					notifyData(new DataEvent(this, s));
				}
				else 
					Thread.sleep(50);
			} catch (Exception e)
			{
				System.out.println("Error while receiving data: " + e.getMessage());
			}
		}
		threadRunning = false;
	}
	
	public void startStreaming()
	{
		if(!threadRunning)
		{
			receiveEnabled = true;
			(new Thread(this)).start();
		}
	}
	
	public void stopStreaming()
	{
		receiveEnabled = false;
	}

	public void setInputStream(InputStream in)
	{
		dataReader = new BufferedReader(new InputStreamReader(in));
	}

	public boolean isRunning()
	{
		return threadRunning;
	}
}
