package de.renew.layoutwindow;

import javax.swing.JMenuItem;

import CH.ifa.draw.DrawPlugin;
import de.renew.draw.ui.api.MenuApi;
import de.renew.draw.ui.ontology.MenuSeparatorFactory;
import de.renew.plugin.PluginProperties;
import de.renew.plugin.annotations.Inject;
import de.renew.plugin.di.DIPlugin;
import de.renew.windowmanagement.Workbench;

/**
 * This plugin adds a menu entry for the Layout Window to the DrawPlugin.
 * It allows users to open a layout window that provides
 * functionality for managing the layout of figures in the drawing.
 *
 * @author haustermann
 */
public class LayoutWindowPlugin extends DIPlugin {

    private static final String LAYOUT_WINDOW = "de.renew.layoutwindow.enable";
    private static final String LAYOUT_WINDOW_MENU_ITEM = "de.renew.layoutwindow.menuitem";
    private static final String LAYOUT_WINDOW_SEPARATOR = "de.renew.layoutwindow.separator";
    private final Workbench _workbench;

    /**
     * Constructs the LayoutWindowPlugin and injects the Workbench dependency.
     *
     * @param workbench the Workbench instance to be used by this plugin
     */
    @Inject
    public LayoutWindowPlugin(Workbench workbench) {
        _workbench = workbench;
    }

    @Override
    public void init() {
        if (PluginProperties.getUserProperties().getBoolProperty(LAYOUT_WINDOW, true)) {
            addLayoutWindowMenuEntry();
        }
    }

    @Override
    public boolean cleanup() {
        DrawPlugin current = DrawPlugin.getCurrent();
        if (current == null) {
            return true;
        }

        MenuApi.unregisterMenu(LAYOUT_WINDOW_SEPARATOR);
        MenuApi.unregisterMenu(LAYOUT_WINDOW_MENU_ITEM);
        return true;
    }

    private void addLayoutWindowMenuEntry() {
        JMenuItem mi = new JMenuItem("Layout Window");
        mi.addActionListener(e -> LayoutWindow.openLayoutWindow(_workbench));

        MenuSeparatorFactory factory = MenuApi.createMenuSeparatorFactory("de.renew.extras");
        JMenuItem separator = factory.createSeparator();

        MenuApi.registerMenu(DrawPlugin.LAYOUT_MENU, separator, LAYOUT_WINDOW_SEPARATOR);
        MenuApi.registerMenu(DrawPlugin.LAYOUT_MENU, mi, LAYOUT_WINDOW_MENU_ITEM);
    }
}