package de.renew.gui;

import java.util.Vector;

import CH.ifa.draw.util.Command;
import de.renew.draw.storables.ontology.Drawing;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.FigureEnumeration;
import de.renew.draw.ui.api.EditorApi;
import de.renew.draw.ui.ontology.DrawingEditor;
import de.renew.draw.ui.ontology.DrawingView;


/**
 * Selects the highlight figures for all selected
 * highlightable figures.
 * <p>
 * HighlightSelectCommand.java
 * Created: Mon Feb 26  2001
 * (Code moved from CPNApplication)
 *
 * @author Frank Wienberg, Michael Duvigneau
 */
public class HighlightSelectCommand extends Command {

    public HighlightSelectCommand(String name) {
        super(name);
    }

    protected DrawingEditor getEditor() {
        return EditorApi.getCurrentEditor();
    }

    /**
     * @return <code>true</code>, if the current drawing is a
     * <code>CPNDrawing</code> and there is at least
     * one figure selected. If there is only one
     * selected figure, it is checked to be a
     * {@link FigureWithHighlight}.
     **/
    @Override
    public boolean isExecutable() {
        if (!super.isExecutable()) {
            return false;
        }
        Drawing drawing = getEditor().drawing();
        DrawingView view = getEditor().view();
        if (drawing instanceof CPNDrawing) {
            if (view.selectionCount() == 1) {
                return (view.selectionElements().nextFigure() instanceof FigureWithHighlight);
            } else {
                return view.selectionCount() > 1;
            }
        }
        return false;
    }

    @Override
    public void execute() {
        if (isExecutable()) {
            DrawingView view = getEditor().view();
            FigureEnumeration figenumeration = view.selectionElements();
            Vector<Figure> highlights = new Vector<>();
            while (figenumeration.hasMoreElements()) {
                Figure fig = figenumeration.nextFigure();
                if (fig instanceof FigureWithHighlight) {
                    Figure hilight = ((FigureWithHighlight) fig).getHighlightFigure();
                    if (hilight != null) {
                        highlights.addElement(hilight);
                    }
                }
            }

            if (highlights.isEmpty()) {
                getEditor().showStatus(
                    "Select some nodes " + "(places or transitions) with highlight figures.");
            } else {
                view.clearSelection();
                view.addToSelectionAll(highlights);


                // Redraw the newly selected elements.
                view.repairDamage();
                getEditor().showStatus("Highlight(s) selected!");
            }
        }
    }
}