package de.ugoe.cs.eventbench.commands;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Shape;
import java.security.InvalidParameterException;
import java.util.List;

import javax.swing.JFrame;

import org.apache.commons.collections15.Transformer;

import de.ugoe.cs.eventbench.data.GlobalDataContainer;
import de.ugoe.cs.eventbench.models.FirstOrderMarkovModel;
import de.ugoe.cs.eventbench.models.FirstOrderMarkovModel.MarkovEdge;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.Console;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.algorithms.layout.ISOMLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position;

public class CMDshowMarkovModel implements Command {

	@Override
	public void help() {
		Console.println("Usage: showMarkovModel <modelName> {<showNodeNames>}");
	}

	@Override
	public void run(List<Object> parameters) {
		String modelname;
		boolean showNodeNames = false;
		try {
			modelname = (String) parameters.get(0);
			if( parameters.size()==2 ) {
				showNodeNames = Boolean.parseBoolean((String) parameters.get(1));
			}
		} catch (Exception e) {
			throw new InvalidParameterException();
		}
		
		Object dataObject = GlobalDataContainer.getInstance().getData(modelname);
		if( dataObject==null ) {
			Console.printerrln("No model with name " + modelname + "found");
		} else {
			FirstOrderMarkovModel mm = (FirstOrderMarkovModel) dataObject;
			
			Graph<String, MarkovEdge> graph = mm.getGraph();
			Layout<String, MarkovEdge> layout = new ISOMLayout<String, MarkovEdge>(graph);
			layout.setSize(new Dimension(1000,800)); // sets the initial size of the space
			// The BasicVisualizationServer<V,E> is parameterized by the edge types
			BasicVisualizationServer<String,MarkovEdge> vv =
			new BasicVisualizationServer<String,MarkovEdge>(layout);
			vv.setPreferredSize(new Dimension(1100,850)); //Sets the viewing area size

			if( showNodeNames ) {
				final Rectangle rect = new Rectangle(240, 20);
				
				Transformer<String, Shape> vertexShapeTransformer =
					new Transformer<String, Shape>() {
						public Shape transform(String s) {
							return rect;
						}
				};
				vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
				vv.getRenderContext().setVertexShapeTransformer(vertexShapeTransformer);
				vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
			}
			
			vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller<MarkovEdge>());
			
			JFrame frame = new JFrame("Markov Model");
			frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
			frame.getContentPane().add(vv);
			frame.pack();
			frame.setVisible(true);
		}
	}
}
