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

package CH.ifa.draw.figures;

import java.awt.Point;
import java.awt.Rectangle;
import java.io.Serial;

import CH.ifa.draw.standard.ChopBoxConnector;
import CH.ifa.draw.util.Geom;
import de.renew.draw.storables.ontology.Figure;

/**
 * PolyLineConnector finds connection points on a
 * PolyLineFigure.
 * {@link PolyLineFigure}
 */
public class PolyLineConnector extends ChopBoxConnector {
    /*
     * Serialization support.
     */
    @Serial
    private static final long serialVersionUID = 6018435940519102865L;

    /**
     * Constructs a new PolyLineConnector.
     */
    public PolyLineConnector() {
        super();
    }

    /**
     * Creates a new PolyLineConnector.
     *
     * @param owner the figure to which this connector is attached
     */
    public PolyLineConnector(Figure owner) {
        super(owner);
    }

    //NOTICE signature

    /**
     * Method to find a point, where the parameter {@code from} can be connected to
     *
     * @param target the figure where the point can be connected to
     * @param from the point that will be connected to the Figure
     * @return a chop {@code Point} where the new point can be connected to
     */
    protected Point chop(Figure target, Point from) {
        PolyLineable p = (PolyLineable) owner();

        // *** based on PolygonFigure's heuristic
        Point ctr = p.center();
        int cx = -1;
        int cy = -1;
        long len = Long.MAX_VALUE;

        // Try for points along edge
        for (int i = 0; i < p.pointCount() - 1; i++) {
            Point p1 = p.pointAt(i);
            Point p2 = p.pointAt(i + 1);
            Point chop = Geom.intersect(p1.x, p1.y, p2.x, p2.y, from.x, from.y, ctr.x, ctr.y);
            if (chop != null) {
                long cl = Geom.length2(chop.x, chop.y, from.x, from.y);
                if (cl < len) {
                    len = cl;
                    cx = chop.x;
                    cy = chop.y;
                }
            }
        }

        // if none found, pick the closest vertex
        if (len == Long.MAX_VALUE) {
            for (int i = 0; i < p.pointCount(); i++) {
                Point pp = p.pointAt(i);
                long l = Geom.length2(pp.x, pp.y, from.x, from.y);
                if (l < len) {
                    len = l;
                    cx = pp.x;
                    cy = pp.y;
                }
            }
        }
        return new Point(cx, cy);
    }

    @Override
    protected Point chop(Figure target, Rectangle source) {
        //NOTICE signature
        return chop(target, Geom.center(source));
    }
}