package unileipzig.isys.neuronviz.app;

import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.awt.BorderLayout;
import java.io.FileNotFoundException;

import unileipzig.isys.neuronviz.kernel.DataStreamer;
import unileipzig.isys.neuronviz.kernel.StreamController;
import unileipzig.isys.neuronviz.kernel.StreamParser;
import unileipzig.isys.neuronviz.kernel.VizManager;
import unileipzig.isys.neuronviz.streamer.FileInputStreamer;
import unileipzig.isys.neuronviz.streamer.StandardInputStreamer;
import unileipzig.isys.neuronviz.viz.NetVisualizer;


/**
 * Class NeuronViz
 */
public class NeuronViz
{
    public NeuronViz(String [] args)
    {
	// create a visualizer manager
	VizManager vizManager = new VizManager();
		
	// create a new visualizer
	NetVisualizer netVisualizer = new NetVisualizer();
		
	// add the visualizers to the manager
	vizManager.addVizPanel(netVisualizer);
				
	// a parser object to parse received Data
	StreamParser parser = new StreamParser();
		
	DataStreamer streamer;
					
	if (args.length == 0)
	    {
		streamer = null; // just for the compiler
		System.err.println("provide lib path!");
		System.exit(1);
	    }
	else if (args.length == 1)
	    {
		streamer = new StandardInputStreamer();
	    }
	else
	    {
		// streamer object to get data into the programm
		streamer = null;
		try
		    {
			System.err.println("test");
			streamer = new FileInputStreamer(args[1]);
		    } catch (FileNotFoundException e)
			{
			    System.out.println("The specified file was not found. Programm will terminate.");
			    e.printStackTrace();
			    System.exit(0);
			}
	    }

		
	// create a stream controller
	StreamController streamController = new StreamController(streamer, args[0]);

	// streamer should inform the parser about new data received
	streamer.addDataListener(parser);
		
	// parser informs visualizer about new parsed data
	parser.addParseListener(netVisualizer);
	parser.addParseListener(streamController);
		
	// the visualizers should control the data streamer
	netVisualizer.setDataStreamer(streamer);
		
	// create main frame and add visualizer manager
	NeuronVizFrame mainFrame = new NeuronVizFrame();
	mainFrame.getContentPane().add(BorderLayout.CENTER,vizManager.getManagerPanel());
	mainFrame.getContentPane().add(BorderLayout.SOUTH,streamController);
		
	// show window
	mainFrame.setVisible(true);

	// start receiving data from the stream if the standard in was selected
	if(streamer instanceof StandardInputStreamer)
	    streamer.startStreaming(1);
    }
	
    public static void main(String[] args)
    {
	// do not react on Ctrl-C anymore
	Signal.handle(new Signal("INT"), new SignalHandler () {
		public void handle(Signal sig) {
		    // do nothing
		}
	    });
	new NeuronViz(args);
    }
}
