/*
 * Fri Feb 28 07:47:13 1997  Doug Lea  (dl at gee)
 * Based on PolyLineHandle
 */

package CH.ifa.draw.contrib;

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

import CH.ifa.draw.standard.AbstractHandle;
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 polygon.
 * @deprecated This class is not to be used externally and will later be hidden.
 */
@Deprecated(since = "5.0", forRemoval = true)
public class PolygonHandle extends AbstractHandle {
    private final int _index;
    private final Locator _locator;

    /**
     * Constructs a polygon handle.
     * @param owner the owning polygon figure.
     * @param l     the locator
     * @param index the index of the node associated with this handle.
     */
    public PolygonHandle(PolygonFigure owner, Locator l, int index) {
        super(owner);
        _locator = l;
        _index = 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();
        }
    }

    @Override
    public void invokeStep(MouseEvent e, int x, int y, int anchorX, int anchorY, DrawingView view) {
        //myOwner().setPointAt(new Point(x, y), fIndex);
        Point p;
        PolygonFigure plf = myOwner();
        if (e.isControlDown() && _index >= 0 && _index < plf.pointCount()) {
            int prevCount = _index - 1;
            int nextCount = _index + 1;
            if (_index == 0) {
                prevCount = plf.pointCount() - 1;
            } else if (_index == plf.pointCount() - 1) {
                nextCount = 0;
            }
            Point prev = plf.pointAt(prevCount);
            Point next = plf.pointAt(nextCount);
            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 invokeEnd(int x, int y, int anchorX, int anchorY, DrawingView view) {
        myOwner().smoothPoints();
        super.invokeEnd(x, y, anchorX, anchorY, view);
    }

    @Override
    public Point locate() {
        return _locator.locate(owner());
    }

    private PolygonFigure myOwner() {
        return (PolygonFigure) owner();
    }
}