package weka.clusterers.forMetisMQI;

import java.awt.Dimension;
import java.util.Iterator;

import javax.swing.JFrame;

import edu.uci.ics.jung.algorithms.layout.CircleLayout;
import edu.uci.ics.jung.algorithms.layout.Layout;
import edu.uci.ics.jung.graph.DirectedSparseGraph;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.visualization.BasicVisualizationServer;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;

public class MQI {
	
	public static void viewGraph(Graph<Node, Edge> g){
		Layout<Node, Edge> layout = new CircleLayout<Node, Edge>(g);
		layout.setSize(new Dimension(300,300)); // sets the initial size of the space
		// The BasicVisualizationServer<V,E> is parameterized by the edge types
		BasicVisualizationServer<Node,Edge> vv =
		new BasicVisualizationServer<Node,Edge>(layout);
		vv.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size
		vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Node>());
		JFrame frame = new JFrame("Simple Graph View");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(vv);
		frame.pack();
		frame.setVisible(true);
	}
	
	static public void start(KLPartition partition) {
		Subgraph A = null;
		Subgraph B = null;
		if(partition.getSubgraph().size() > partition.getComplement().size()) {
			A = partition.getSubgraph();
			B = partition.getComplement();
		}
		else {
			A = partition.getComplement();
			B = partition.getSubgraph();
		}
		int a = A.size();
		int c = partition.edgeCut();
		
		
		Graph<Node,Edge> g = new DirectedSparseGraph<Node, Edge>();
		Iterator<Integer> nodes =  A.iterator();
		while(nodes.hasNext()) {
			int u = nodes.next();
			g.addVertex(new Node(Integer.toString(u)));
		}
		
		nodes =  A.iterator();
		int id = 0;
		while(nodes.hasNext()) {
			int u = nodes.next();
			Iterator<Integer> neighbors = A.getNeighbours(u).iterator();
			while(neighbors.hasNext()) {
				int v = neighbors.next();
				g.addEdge(new Edge(Integer.toString(id),A.getWeight(u, v),a),new Node(Integer.toString(u)),new Node(Integer.toString(v)));
				id++;
			}
		}
		
		Node source = new Node("S");
		Node sink = new Node("T");
		g.addVertex(source);
		g.addVertex(sink);
		
		
		nodes =  B.iterator();
		while(nodes.hasNext()) {
			int u = nodes.next();
			Iterator<Integer> neighbors = B.getGraph().getNeighbors(u).iterator();
			while(neighbors.hasNext()) {
				int v = neighbors.next();
				if(A.contains(v)) {
					g.addEdge(new Edge(Integer.toString(id),1,a),source,new Node(Integer.toString(v)));
					id++;
				}
			}
		}
		
		nodes =  A.iterator();
		while(nodes.hasNext()) {
			int u = nodes.next();
			g.addEdge(new Edge(Integer.toString(id),1,c),new Node(Integer.toString(u)),sink);
			id++;
		}
		
		viewGraph(g);
		System.out.println(g.toString());
		
	}
	
}
