package dfatool.views.graph;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.zest.core.viewers.GraphViewer;
import org.eclipse.zest.core.widgets.Graph;
import org.eclipse.zest.layouts.LayoutAlgorithm;
import org.eclipse.zest.layouts.algorithms.SpringLayoutAlgorithm;

import patterns.Observer;
import dfatool.strategy.graph.CommunicationGraph;
import dfatool.strategy.graph.IGraph;



public class GraphView extends ViewPart{

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "dfatool.views.graph.GraphView";

	private Graph graph;
	private int layout = 1;
	private GraphViewer viewer;

	private IAction refresh;
	public void createPartControl(Composite parent) {
		
		viewer = new GraphViewer(parent, SWT.BORDER);
		viewer.setContentProvider(new NodesContentProvider());
		viewer.setLabelProvider(new NodesLabelProvider());
		LayoutAlgorithm layout = setLayout();
		viewer.setLayoutAlgorithm(layout, true);
		viewer.applyLayout();
		
		makeActions();
		contributeToActionBars();
	}
	
	
	
	  private LayoutAlgorithm setLayout() {
		    LayoutAlgorithm layout;
		    layout = new SpringLayoutAlgorithm();
		    return layout;
	
	}
	  
	  private void contributeToActionBars() {
			IActionBars bars = getViewSite().getActionBars();
			fillLocalToolBar(bars.getToolBarManager());
		}


		private void fillLocalToolBar(IToolBarManager manager) {
			manager.add(refresh);
		}

		private void makeActions() {
			refresh = new Action() {
				public void run() {
					asyncRefresh();
				}
			};
			refresh.setText("Refresh");
			refresh.setToolTipText("Refresh view");
			
		}

		  
		  

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub
		
	}
	
	

	public void asyncRefresh() {
		PlatformUI.getWorkbench().getDisplay().asyncExec(
				new Runnable() {
				      @Override
				      public void run() {
				        refresh();
				      }
				    }); 
	}
	
	private void refresh(){
		IGraph graph = CommunicationGraph.getInstance().getGraph();
	    if(graph != null){
	    	viewer.setInput(graph.getNodes());
	      	viewer.refresh();
	     }
	}

	
}