package de.prob2.ui.groovy;

import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.shape.Path;

public class GroovyCodeCompletion {
	
	private ContextMenu suggestions;
	
	public GroovyCodeCompletion() {
		suggestions = new ContextMenu(new MenuItem("boo"));
	}
	
	public void activate(GroovyConsole console) {
		Point2D point = findCaretPosition(findCaret(console));
		double x = point.getX() + 10;
		double y = point.getY() + 10;
		suggestions.show(console, x, y);
	}
	
	public void deactivate() {
		suggestions.hide();
	}
	
	public boolean isVisible() {
		return suggestions.isShowing();
	}
	
	
	private Path findCaret(Parent parent) {
		for (Node node : parent.getChildrenUnmodifiable()) {
			if (node instanceof Path) {
				return (Path) node;
			} else if (node instanceof Parent) {
				Path caret = findCaret((Parent) node);
				if (caret != null) {
					return caret;
				}
			}
		}
		return null;
	}
	

	private Point2D findCaretPosition(Node node) {
		double x = 0;
		double y = 0;
		for (Node n = node; n != null; n=n.getParent()) {
			Bounds parentBounds = n.getBoundsInParent();
			x += parentBounds.getMinX();
			y += parentBounds.getMinY();
		}
		if(node.getScene() != null) {
			Scene scene = node.getScene();
			x += scene.getX() + scene.getWindow().getX();
			y += scene.getY() + scene.getWindow().getY();
			x = Math.min(scene.getWindow().getX() + scene.getWindow().getWidth() - 20, x);
			y = Math.min(scene.getWindow().getY() + scene.getWindow().getHeight() - 20, y);
		}
		return new Point2D(x,y);
	}

}

@@ -245,16 +245,56 @@
 nuItem;%0A
+import javafx.scene.control.ScrollPane;%0A
 import j
@@ -317,16 +317,16 @@
 e.Path;%0A
-
 %0Apublic 
@@ -392,16 +392,42 @@
 ions;%0A%09%0A
+%09private ScrollPane sp;%0A%09%0A
 %09public 
@@ -447,24 +447,51 @@
 pletion() %7B%0A
+%09%09//sp = new ScrollPane();%0A
 %09%09suggestion
@@ -529,16 +529,556 @@
 m(%22boo%22)
+, new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22), new MenuItem(%22boo%22));%0A%09%09//sp.setContextMenu(suggestions
 );%0A%09%7D%0A%09%0A
@@ -1789,16 +1789,16 @@
  x = 0;%0A
-
 %09%09double
@@ -1805,16 +1805,57 @@
  y = 0;%0A
+%09%09if(node == null) %7B%0A%09%09%09return null;%0A%09%09%7D%0A
 %09%09for (N

Fix possible NullPointerException in Groovy Code Completion