package brn.gui.linktable.diagram.actions;

import java.util.List;

import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import brn.gui.linktable.diagram.edit.parts.GraphEditPart;
import brn.gui.linktable.diagram.edit.parts.NodeEditPart;

public class ShowNodeLinksAction implements IObjectActionDelegate {


  private NodeEditPart selectedElement;

  public void run(IAction action) {
    if (null == selectedElement)
      return;

    GraphEditPart graphEditPart = (GraphEditPart)selectedElement.getParent();
    List listNode = graphEditPart.getChildren();

    for (int i = 0; i < listNode.size(); i++) {
      NodeEditPart nodeEditPart = (NodeEditPart) listNode.get(i);

      if (nodeEditPart.equals(selectedElement))
        continue;

      List edges = nodeEditPart.getSourceConnections();
      for (int j = 0; j < edges.size(); j++) {
        GraphicalEditPart edge = (GraphicalEditPart) edges.get(j);
        edge.getFigure().setVisible(false);
      }
    }

    List edges = selectedElement.getSourceConnections();
    for (int j = 0; j < edges.size(); j++) {
      GraphicalEditPart edge = (GraphicalEditPart) edges.get(j);
      edge.getFigure().setVisible(true);
    }

    edges = selectedElement.getTargetConnections();
    for (int j = 0; j < edges.size(); j++) {
      GraphicalEditPart edge = (GraphicalEditPart) edges.get(j);
      edge.getFigure().setVisible(true);
    }
  }

  public void selectionChanged(IAction action, ISelection selection) {
    selectedElement = null;
    if (selection instanceof IStructuredSelection) {
      IStructuredSelection structuredSelection = (IStructuredSelection) selection;
      if (structuredSelection.getFirstElement() instanceof NodeEditPart) {
        selectedElement = (NodeEditPart) structuredSelection.getFirstElement();
      }
    }
  }

  public void setActivePart(IAction action, IWorkbenchPart targetPart) {
  }

}
