/* ----------------------------------------
 * Origin  : GFI INFORMATIQUE 
 * Project : CDPP Propagation Tool 
 * ----------------------------------------
 * History 
 * Version : 01/05/2015 : SCA : V2.1
 * Version : 29/06/2022 : LBE : V2.5
 * DM-ID : Redmine#9582 : 30/06/2022 : vplot data range is made by selecting a date from catalogue in menu
 * ----------------------------------------
 */
package fr.tlse.irap.pt.client.controller.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;

public class MapMenu extends ContextMenu {

    private Map<Item, ISelectedItem> map;

    public MapMenu() {
        super();
        map = new HashMap<Item, ISelectedItem>();
    }

    public Map<Item, ISelectedItem> getMap() {
        return map;
    }

    /**
     * iterative function that allows the creation of the menu.
     *
     * @param items
     * @return
     */
    public void addAll(Collection<Item> items) {
        getItems().addAll(createGlobalContextMenu(items));
    }

    public void removeAll() {
        getItems().clear();
    }

    private List<MenuItem> createGlobalContextMenu(Collection<Item> items) {

        List<MenuItem> menus = new ArrayList<MenuItem>();

        for (final Item item : items) {
            if (item.hasChild()) {
                Menu menu = new Menu(item.getName());
                menu.getItems().addAll(createGlobalContextMenu(item.getChild()));
                menus.add((Menu) menu);
            } else {
                final MenuItem menuItem = new MenuItem(item.getName());
                menuItem.setOnAction(new EventHandler<ActionEvent>() {

                    @Override
                    public void handle(ActionEvent event) {
                        // the value could be null if it hasn't registered
                        // previously
                        if (map.get(item) != null) {
                            map.get(item).run();
                        }
                    }
                });
                menus.add(menuItem);
            }
        }

        return menus;
    }

    /**
     *
     * @param name
     * @return
     */
    public Menu getMenu(String name) {
        for (MenuItem item : getItems()) {
            if (item.getText().contains(name)) {
                return (Menu) item;
            }
        }

        return null;
    }

    public MenuItem getMenuItem(String name) {
        for (MenuItem item : getItems()) {
            if (item.getText().contains(name)) {
                return item;
            }
        }

        return null;
    }

}
