package de.renew.draw.ui.impl.menus.internal;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

import CH.ifa.draw.application.DrawApplication;

/**
 * Helper class providing utility methods for menu creation.
 */
public final class MenuHelper {

    private MenuHelper() {}

    /**
     * Creates a menu item with the given name, shortcut and action.
     *
     * @param name     the name of the menu item
     * @param shortcut the shortcut for the menu item as the keycode representing the key (e.g. {@link KeyEvent#VK_R})
     * @param action the action to be performed when the menu item is clicked
     * @return the created menu item
     */
    public static JMenuItem createMenuItem(String name, int shortcut, Runnable action) {
        JMenuItem menuItem;
        if (shortcut == 0) {
            menuItem = new JMenuItem(name);
        } else {
            menuItem = new JMenuItem(name, shortcut);
            menuItem.setAccelerator(
                KeyStroke.getKeyStroke(
                    shortcut, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
        }
        menuItem.setFont(DrawApplication.getMenuFont());
        menuItem.addActionListener(event -> action.run());
        return menuItem;
    }

    /**
     * Creates a menu item with the given name and action.
     *
     * @param name   the name of the menu item.
     * @param action the action to be performed when the menu item is clicked
     * @return the created menu item
     */
    public static JMenuItem createMenuItem(String name, Runnable action) {
        return createMenuItem(name, 0, action);
    }

}
