package de.codecentric.centerdevice.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class MenuBarUtils {
	public static MenuBar createMenuBar(List<Menu> menus) {
		MenuBar bar = new MenuBar();
		bar.setUseSystemMenuBar(true);
		bar.getMenus().addAll(menus);
		return bar;
	}

	public static void removeExistingMenuBar(Pane pane) {
		ObservableList<Node> children = pane.getChildren();
		children.removeAll(children.stream().filter(node -> node instanceof MenuBar).collect(Collectors.toList()));
	}

	public static void setMenuBar(Stage stage, MenuBar menuBar) {
		Parent parent = stage.getScene().getRoot();
		if (parent instanceof Pane) {
			setMenuBar((Pane) parent, menuBar);
		}
	}

	public static void setMenuBar(Pane pane, MenuBar menuBar) {
		replaceMenuBar(pane, createMenuBar(extractSubMenus(menuBar)));
	}

	private static void replaceMenuBar(Pane pane, MenuBar createMenuBar) {
		removeExistingMenuBar(pane);
		pane.getChildren().add(createMenuBar);
	}

	private static List<Menu> extractSubMenus(MenuBar bar) {
		if (bar.getMenus().size() <= 1) {
			return new ArrayList<>();
		}
		return bar.getMenus().subList(1, bar.getMenus().size());
	}
}

@@ -162,24 +162,51 @@
 rvableList;%0A
+import javafx.scene.Group;%0A
 import javaf
@@ -624,23 +624,8 @@
 Bar(
-Pane pane) %7B%0A%09%09
 Obse
@@ -653,30 +653,11 @@
 dren
- = pane.getChildren();
+) %7B
 %0A%09%09c
@@ -876,16 +876,205 @@
 Root();%0A
+%09%09ObservableList%3CNode%3E children = getChildren(parent);%0A%09%09if (children != null) %7B%0A%09%09%09setMenuBar(children, menuBar);%0A%09%09%7D%0A%09%7D%0A%0A%09private static ObservableList%3CNode%3E getChildren(Parent parent) %7B%0A
 %09%09if (pa
@@ -1100,26 +1100,23 @@
 e) %7B%0A%09%09%09
-setMenuBar
+return 
 ((Pane) 
@@ -1125,110 +1125,346 @@
 rent
-, menuBar);%0A%09%09%7D%0A%09%7D%0A%0A%09public static void setMenuBar(Pane pane, MenuBar menuBar) %7B%0A%09%09replaceMenuBar(pane
+).getChildren();%0A%09%09%7D else if (parent instanceof Group) %7B%0A%09%09%09return ((Group) parent).getChildren();%0A%09%09%7D%0A%0A%09%09return null;%0A%09%7D%0A%0A%09public static void setMenuBar(Pane pane, MenuBar menuBar) %7B%0A%09%09setMenuBar(pane.getChildren(), menuBar);%0A%09%7D%0A%0A%09private static void setMenuBar(ObservableList%3CNode%3E children, MenuBar menuBar) %7B%0A%09%09replaceMenuBar(children
 , cr
@@ -1539,33 +1539,53 @@
 laceMenuBar(
-Pane pane
+ObservableList%3CNode%3E children
 , MenuBar cr
@@ -1627,35 +1627,29 @@
 Bar(
-pane);%0A%09%09pane.getC
+children);%0A%09%09c
 hildren
-()
 .add

Add menu bar to Groups in addition to Panes