/*
 * @(#)ConnectedTextTool.java 5.1
 *
 */

package CH.ifa.draw.figures;

import java.awt.event.MouseEvent;

import CH.ifa.draw.framework.ChildFigure;
import CH.ifa.draw.framework.ParentFigure;
import CH.ifa.draw.standard.TextHolder;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.ui.ontology.DrawingEditor;

/**
 * Tool to create new or edit existing text figures.
 * A new text figure is connected with the clicked figure.
 * <p>
 * {@link TextHolder}
 */
public class ConnectedTextTool extends TextTool {
    public boolean _connected = false;
    private final boolean _mustConnect;

    /**
     * Creates a new ConnectedTextTool within the given editor context and with a prototype to clone.
     * Assumes that the operation must connect by default.
     *
     * @param editor the editor context within which to work
     * @param prototype the prototype TextFigure which will be cloned.
     */
    public ConnectedTextTool(DrawingEditor editor, TextFigure prototype) {
        this(editor, prototype, true);
    }

    /**
     * Creates a new ConnectedTextTool with control over whether the operation must connect or not.
     *
     * @param editor the editor context within which to work
     * @param prototype the prototype TextFigure to clone.
     * @param mustConnect boolean control over whether created text figure must connect with a parent figure or not
     */
    public ConnectedTextTool(DrawingEditor editor, TextFigure prototype, boolean mustConnect) {
        super(editor, prototype);
        _mustConnect = mustConnect;
    }

    /**
     * If the pressed figure is a TextHolder it can be edited otherwise
     * a new text figure is created.
     */
    @Override
    public void mouseDown(MouseEvent e, int x, int y) {
        if (_connected || isTypingActive()) {
            super.mouseDown(e, x, y);
        } else {
            Figure pressedFigure = drawing().findFigureInside(x, y);
            boolean pressedEditable = (pressedFigure instanceof TextHolder)
                && ((TextHolder) pressedFigure).acceptsTyping();

            if (pressedFigure instanceof ParentFigure
                && ((ChildFigure) getPrototype()).canBeParent((ParentFigure) pressedFigure)) {
                super.mouseDown(e, x, y);
                ChildFigure child = (ChildFigure) createdFigure();
                if (child != null) {
                    child.setParent((ParentFigure) pressedFigure);
                    _connected = true;
                }
            } else if (!_mustConnect || pressedEditable) {
                super.mouseDown(e, x, y);
            }
        }
    }

    /**
     * If the pressed figure is a TextHolder it can be edited otherwise
     * a new text figure is created.
     */
    @Override
    public void activate() {
        super.activate();
        _connected = false;
    }
}