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

package CH.ifa.draw.standard;

import java.awt.event.MouseEvent;

import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.ui.ontology.DrawingEditor;


/**
 * DragTracker implements the dragging of the clicked
 * figure.
 *
 * @see SelectionTool
 */
public class DragTracker extends AbstractTool {
    protected Figure fAnchorFigure;
    private int _lastX; // previous mouse position
    private int _lastY; // previous mouse position
    private boolean _moved = false;

    public DragTracker(DrawingEditor editor, Figure anchor) {
        super(editor);
        fAnchorFigure = anchor;
        editor().prepareUndoSnapshot();
    }

    @Override
    public void mouseDown(MouseEvent e, int x, int y) {
        super.mouseDown(e, x, y);
        _lastX = x;
        _lastY = y;

        if (e.isShiftDown()) {
            view().toggleSelection(fAnchorFigure);
            fAnchorFigure = null;
        } else if (!view().selection().contains(fAnchorFigure)) {
            view().clearSelection();
            view().addToSelection(fAnchorFigure);
        }

        altKeyBehavior(e);
    }

    @Override
    public void mouseDrag(MouseEvent e, int x, int y) {
        super.mouseDrag(e, x, y);
        _moved = (Math.abs(x - _anchorX) > 4) || (Math.abs(y - _anchorY) > 4);

        if (_moved) {
            drag(x - _lastX, y - _lastY);
        }
        _lastX = x;
        _lastY = y;

        altKeyBehavior(e);
    }

    protected void drag(int dx, int dy) {
        view().moveSelection(dx, dy);
    }

    @Override
    public void mouseUp(MouseEvent e, int x, int y) {
        if (_moved) {
            editor().commitUndoSnapshot();
        }
        super.mouseUp(e, x, y);
    }

    /**
     * Sets a flag on the anchor figure based on whether the Alt key is pressed.
     * If Alt is down, child figures will move with the parent; otherwise, the flag is cleared.
     *
     * @param e the mouse event triggering the Alt key behavior check
     */
    public void altKeyBehavior(MouseEvent e) {
        if (fAnchorFigure != null) {
            if (e.isAltDown()) {
                fAnchorFigure.setAttribute("MoveWithChildren", true);
            } else {
                fAnchorFigure.setAttribute("MoveWithChildren", null);
            }
        }
    }
}