package de.renew.gui;

import java.util.List;

import CH.ifa.draw.framework.UndoableCommand;
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.DrawingView;


/**
 * Associates a highlight figure to a highlightable figure.
 * <p>
 * HighlightAssociateCommand.java
 * Created: Mon Feb 26  2001
 * (Code moved from CPNApplication)
 *
 * @author Frank Wienberg, Michael Duvigneau
 */
public class HighlightAssociateCommand extends UndoableCommand {

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


    /**
     * @return <code>true</code>, if the current drawing is a
     * <code>CPNDrawing</code>, there are exactly two
     * selected figures and one of them is a
     * {@link FigureWithHighlight}.
     **/
    @Override
    public boolean isExecutable() {
        if (!super.isExecutable()) {
            return false;
        }
        Drawing drawing = EditorApi.getCurrentDrawing();
        DrawingView view = getEditor().view();
        if (drawing instanceof CPNDrawing && view.selectionCount() == 2) {
            FigureEnumeration sel = view.selectionElements();
            while (sel.hasMoreElements()) {
                if (sel.nextFigure() instanceof FigureWithHighlight) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean executeUndoable() {
        if (isExecutable()) {
            if (!super.isExecutable()) {
                return false;
            }


            // The isExecutable() assertions are neccessary.
            // Otherwise, there would be errors in the following
            // code...
            CPNDrawing drawing = (CPNDrawing) EditorApi.getCurrentDrawing();
            DrawingView view = getEditor().view();
            List<Figure> vfig = view.selection();
            int pos = -1;
            if (vfig.get(0) instanceof FigureWithHighlight) {
                pos = 0;
            } else if (vfig.get(1) instanceof FigureWithHighlight) {
                pos = 1;
            }
            FigureWithHighlight nf = (FigureWithHighlight) vfig.get(pos);
            Figure fig = vfig.get(1 - pos);
            drawing.setHighlightFigure(nf, fig);
            getEditor().showStatus("Highlight associated!");
            return true;
        }
        getEditor().showStatus("Select a node (place or transition) and another figure!");
        return false;
    }
}