// All Rights Reserved. Copyright (C) Kazuo Misue (2010)

import java.io.IOException;

import javax.swing.JFrame;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.collections15.BidiMap;
import org.apache.commons.collections15.Factory;
import org.xml.sax.SAXException;

import edu.uci.ics.jung.algorithms.layout.FRLayout;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.UndirectedSparseGraph;
import edu.uci.ics.jung.io.GraphMLReader;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer.VertexLabel.Position;

public class Sample7a2 {
	
	protected static Graph<MyNode,MyEdge> readFile(String filename) throws ParserConfigurationException, SAXException, IOException {
		Factory<MyNode> nodeFactory = new Factory<MyNode>() {
			@Override
			public MyNode create() {
				return new MyNode(""); 
			}
		};
		
		Factory<MyEdge> edgeFactory = new Factory<MyEdge>() {
			@Override
			public MyEdge create() {
				return new MyEdge("");
			}
		};
		
		GraphMLReader<Graph<MyNode,MyEdge>, MyNode,MyEdge> graphMLReader = new GraphMLReader<Graph<MyNode,MyEdge>, MyNode,MyEdge>(nodeFactory, edgeFactory);
    	Graph<MyNode,MyEdge> graph = new UndirectedSparseGraph<MyNode,MyEdge>();
    	graphMLReader.load(filename, graph);
    	
        final BidiMap<MyNode, String> nodeIds = graphMLReader.getVertexIDs();        
		for (MyNode node : graph.getVertices()) {
		    node.label = nodeIds.get(node);
		}
		return graph;
    }

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
    	String filename = "data/sample-data1.xml";
        Graph<MyNode,MyEdge> graph = readFile(filename);
        VisualizationViewer<MyNode,MyEdge> panel = new VisualizationViewer<MyNode,MyEdge>(new FRLayout<MyNode,MyEdge>(graph));
        panel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<MyNode>());
        panel.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
        
        JFrame frame = new JFrame("Graph View: Reading GraphML(2)");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
    
}
