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

package CH.ifa.draw.figures;

import java.awt.Point;
import java.awt.event.MouseEvent;

import CH.ifa.draw.standard.LocatorHandle;
import CH.ifa.draw.util.Geom;
import de.renew.draw.storables.ontology.Locator;
import de.renew.draw.ui.ontology.DrawingView;

/**
 * A handle for a node on the polyline.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
@SuppressWarnings("removal")
public class PolyLineHandle extends LocatorHandle {
    private final int _index;

    /**
     * Creates a new PolyLineHandle.
     *
     * @param owner the polyline figure this handle belongs to
     * @param l the locator used to position the handle
     * @param index the index of the node in the polyline that this handle manipulates
     */
    public PolyLineHandle(PolyLineable owner, Locator l, int index) {
        super(owner, l);
        _index = index;
    }

    @Override
    public void invokeStep(MouseEvent e, int x, int y, int anchorX, int anchorY, DrawingView view) {
        Point p;
        PolyLineable plf = myOwner();
        if (e.isControlDown() && _index > 0 && _index < plf.pointCount() - 1) {
            Point prev = plf.pointAt(_index - 1);
            Point next = plf.pointAt(_index + 1);
            Point corner1 = new Point(prev.x, next.y);
            Point corner2 = new Point(next.x, prev.y);
            if (Geom.length(x, y, corner1.x, corner1.y) < Geom.length(x, y, corner2.x, corner2.y)) {
                p = corner1;
            } else {
                p = corner2;
            }
        } else {
            p = new Point(x, y);
        }
        myOwner().setPointAt(p, _index);
    }

    @Override
    public void invokeStart(MouseEvent e, int x, int y, DrawingView view) {
        super.invokeStart(e, x, y, view);
        if (e.getClickCount() > 1) {
            myOwner().removePointAt(_index);
            view.selectionInvalidateHandles();
        }
    }

    /**
     * Getter Method for the node's index.
     *
     * @return index
     */
    protected int getIndex() {
        return _index;
    }

    /**
     * Getter method for the Owner.
     *
     * @return {@code PolyLineable} Owner of the instance
     */
    protected PolyLineable myOwner() {
        return (PolyLineable) owner();
    }
}