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

package CH.ifa.draw.figures;

import java.awt.Point;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serial;
import java.util.Vector;

import CH.ifa.draw.standard.ChangeConnectionEndHandle;
import CH.ifa.draw.standard.ChangeConnectionStartHandle;
import CH.ifa.draw.standard.FigureEnumerator;
import CH.ifa.draw.standard.MergedFigureEnumerator;
import de.renew.draw.storables.api.StorableApi;
import de.renew.draw.storables.ontology.ConnectionFigure;
import de.renew.draw.storables.ontology.Connector;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.FigureChangeEvent;
import de.renew.draw.storables.ontology.FigureEnumeration;
import de.renew.draw.storables.ontology.StorableInput;
import de.renew.draw.storables.ontology.StorableOutput;
import de.renew.draw.ui.ontology.FigureHandle;

/**
 * A LineConnection is a standard implementation of the
 * ConnectionFigure interface. The interface is implemented with PolyLineFigure.
 * <p>
 * {@link ConnectionFigure}
 */
public class LineConnection extends PolyLineFigure implements ConnectionFigure {
    /*
     * Serialization support.
     */
    @Serial
    private static final long serialVersionUID = 6883731614578414801L;

    /**
     * The connector where the start of the line is
     * connected to.
     *
     * @serial
     **/
    protected Connector fStart = null;

    /**
     * The connector where the end of the line is
     * connected to.
     *
     * @serial
     **/
    protected Connector fEnd = null;
    /**
     * Unused serial version number.
     */
    @SuppressWarnings("unused")
    private final int _lineConnectionSerializedDataVersion = 1;

    /**
     * Constructs a LineConnection. A connection figure has
     * an arrow decoration at the start and end.
     */
    public LineConnection() {
        super(4);
        setStartDecoration();
        setEndDecoration();
    }

    /**
     * Constructs a LineConnection. A connection figure has
     * an arrow decoration at the start and end.
     *
     * @param start the arrow decoration at the start of the line
     * @param end the arrow decoration at the end of the line
     * @param lineStyle the lineStyle that should be used
     */
    public LineConnection(LineDecoration start, LineDecoration end, String lineStyle) {
        super(2);
        setStartDecoration(start);
        setEndDecoration(end);
        setLineStyle(lineStyle);
    }

    /**
     * Tests whether a figure can be a connection target.
     * ConnectionFigures cannot be connected and return false.
     */
    @Override
    public boolean canConnect() {
        return false;
    }

    /**
     * Ensures that a connection is updated if the connection
     * was moved.
     */
    @Override
    protected void basicMoveBy(int dx, int dy) {
        (fPoints.firstElement()).translate(-dx, -dy);
        (fPoints.lastElement()).translate(-dx, -dy);
        super.basicMoveBy(dx, dy);

        updateConnection(); // make sure that we are still connected
    }

    /**
     * Sets the start figure of the connection.
     */
    @Override
    public void connectStart(Connector start) {
        fStart = start;
        startFigure().addFigureChangeListener(this);
        // fuw:
        if (fStart != null && fEnd != null) {
            handleAdjust(startFigure(), endFigure());
        } else {
            handleConnect(startFigure(), endFigure());
        }
        if (GUI_LOGGER.isTraceEnabled()) {
            GUI_LOGGER.trace("LineConnection: set start of " + this + " to " + this.startFigure());
        }
    }

    /**
     * Sets the end figure of the connection.
     */
    @Override
    public void connectEnd(Connector end) {
        Connector oldEnd = fEnd;
        fEnd = end;
        endFigure().addFigureChangeListener(this);
        if (oldEnd == null) {
            handleConnect(startFigure(), endFigure());
        } else {
            handleAdjust(startFigure(), endFigure());
        }
        if (GUI_LOGGER.isTraceEnabled()) {
            GUI_LOGGER.trace("LineConnection: set end of " + this + " to " + this.endFigure());
        }
    }

    /**
     * Disconnects the start figure.
     */
    @Override
    public void disconnectStart() {
        handleDisconnect(startFigure(), endFigure()); // fuw
        startFigure().removeFigureChangeListener(this);
        fStart = null;
    }

    /**
     * Disconnects the end figure.
     */
    @Override
    public void disconnectEnd() {
        handleDisconnect(startFigure(), endFigure());
        endFigure().removeFigureChangeListener(this);
    }

    /**
     * Tests whether a connection connects the same figures
     * as another ConnectionFigure.
     */
    @Override
    public boolean connectsSame(ConnectionFigure other) {
        return other.start() == start() && other.end() == end();
    }

    /**
     * Handles the disconnection of a connection.
     * Override this method to handle this event.
     *
     * @param start the start figure of this current connection
     * @param end the end figure of this current connection
     */
    protected void handleDisconnect(Figure start, Figure end) {}

    /**
     * Handles the adjustment of a connection.
     * Override this method to handle this event.
     *
     * @param start the start figure of this current connection
     * @param end the end figure of this current connection
     */
    protected void handleAdjust(Figure start, Figure end) {}

    /**
     * Handles the connection of a connection.
     * Override this method to handle this event.
     *
     * @param start the start figure of this connection
     * @param end the end figure of this connection
     */
    protected void handleConnect(Figure start, Figure end) {}

    /**
     * Gets the start figure of the connection.
     *
     * @return start figure or null if not existent
     */
    public Figure startFigure() {
        if (start() != null) {
            return start().owner();
        }
        return null;
    }

    /**
     * Gets the end figure of the connection.
     *
     * @return end figure or null if nor existent
     */
    public Figure endFigure() {
        if (end() != null) {
            return end().owner();
        }
        return null;
    }

    /**
     * Gets the start figure of the connection.
     */
    @Override
    public Connector start() {
        return fStart;
    }

    /**
     * Gets the end figure of the connection.
     */
    @Override
    public Connector end() {
        return fEnd;
    }

    /**
     * Tests whether two figures can be connected.
     */
    @Override
    public boolean canConnect(Figure start, Figure end) {
        return true;
    }

    /**
     * Sets the start point.
     */
    @Override
    public void startPoint(int x, int y) {
        willChange();

        // We have to call super methods since the point-
        // modifying methods of this class would try to update
        // the connection and call this method again.
        if (fPoints.isEmpty()) {
            super.addPoint(x, y);
        } else {
            super.setPointAt(new Point(x, y), 0);
        }

        // changed(); not needed since the called methods do it
    }

    @Override
    public void startPoint(Point p) {
        startPoint(p.x, p.y);
    }

    /**
     * Sets the end point.
     */
    @Override
    public void endPoint(int x, int y) {
        willChange();

        // We have to call super methods because the point-
        // modifying methods of this class would try to update
        // the connection and call this method again.
        if (fPoints.size() < 2) {
            super.addPoint(x, y);
        } else {
            super.setPointAt(new Point(x, y), fPoints.size() - 1);
        }

        // changed(); not needed since the called methods do it
    }

    @Override
    public void endPoint(Point p) {
        endPoint(p.x, p.y);
    }

    /**
     * Gets the start point.
     */
    @Override
    public Point startPoint() {
        Point p = fPoints.firstElement();
        return new Point(p.x, p.y);
    }

    /**
     * Gets the end point.
     */
    @Override
    public Point endPoint() {
        Point p = fPoints.lastElement();
        return new Point(p.x, p.y);
    }

    /**
     * Gets the handles of the figure. It returns the normal
     * PolyLineHandles but adds ChangeConnectionHandles at the
     * start and end.
     */
    @Override
    public Vector<FigureHandle> handles() {
        int n = fPoints.size();
        Vector<FigureHandle> handles = new Vector<>(2 * n);
        handles.addElement(new ChangeConnectionStartHandle(this));
        addIntermediateHandles(handles);
        handles.addElement(new ChangeConnectionEndHandle(this));
        return handles;
    }

    /**
     * Sets the point and updates the connection.
     */
    @Override
    public void setPointAt(Point p, int i) {
        super.setPointAt(p, i);
        layoutConnection();
    }

    /**
     * Inserts the point and updates the connection.
     */
    @Override
    public void insertPointAt(Point p, int i) {
        super.insertPointAt(p, i);
        layoutConnection();
    }

    /**
     * Removes the point and updates the connection.
     */
    @Override
    public void removePointAt(int i) {
        super.removePointAt(i);
        layoutConnection();
    }

    /**
     * Updates the connection.
     */
    @Override
    public void updateConnection() {
        if (fStart != null) {
            Point start = fStart.findStart(this);
            startPoint(start.x, start.y);
        }
        if (fEnd != null) {
            Point end = fEnd.findEnd(this);
            endPoint(end.x, end.y);
        }
    }

    /**
     * Lays out the connection. This is called when the connection
     * itself changes. By default, the connection is recalculated.
     */
    public void layoutConnection() {
        updateConnection();
    }

    @Override
    public void figureChanged(FigureChangeEvent e) {
        updateConnection();
    }

    @Override
    public void figureHandlesChanged(FigureChangeEvent e) {}

    @Override
    public void figureRemoved(FigureChangeEvent e) {
        if (listener() != null) {
            listener().figureRequestRemove(StorableApi.createFigureChangeEvent(this));
        }
    }

    @Override
    public void figureRequestRemove(FigureChangeEvent e) {}

    @Override
    public void figureInvalidated(FigureChangeEvent e) {}

    @Override
    public void figureRequestUpdate(FigureChangeEvent e) {}

    @Override
    public void release() {
        super.release();
        if (fStart != null && fEnd != null) {
            handleDisconnect(startFigure(), endFigure()); // cannot handle null parameters
        }
        if (fStart != null) {
            startFigure().removeFigureChangeListener(this);
        }
        if (fEnd != null) {
            endFigure().removeFigureChangeListener(this);
        }
    }

    /**
     * Returns the figures with dependencies of superclasses
     * plus the two figures to which this line is connected
     * to. Unlike the parent/child symmetry the connector
     * figures don't report this connection as a dependency.
     * So it is possible to duplicate the figures without
     * duplicating all its connections.
     **/
    @Override
    public FigureEnumeration getFiguresWithDependencies() {
        FigureEnumeration superDep = super.getFiguresWithDependencies();
        Vector<Figure> myDep = new Vector<>(2);
        myDep.addElement(start().owner());
        myDep.addElement(end().owner());
        return new MergedFigureEnumerator(superDep, new FigureEnumerator(myDep));
    }

    @Override
    public void write(StorableOutput dw) {
        super.write(dw);
        dw.writeStorable(fStart);
        dw.writeStorable(fEnd);
    }

    @Override
    public void read(StorableInput dr) throws IOException {
        super.read(dr);
        Connector start = (Connector) dr.readStorable();
        if (start != null) {
            connectStart(start);
        }
        Connector end = (Connector) dr.readStorable();
        if (end != null) {
            connectEnd(end);
        }
        if (start != null && end != null) {
            updateConnection();
        }
    }

    /**
     * Deserialization method, behaves like default readObject
     * method except reconnecting itself to the <code>fStart
     * </code>and <code>fEnd</code> connectors again.
     *
     * @param s the stream that will be deserialized
     * @throws ClassNotFoundException thrown when no class can be found
     * @throws IOException when an I/O error occurs
     **/
    @Serial
    private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
        s.defaultReadObject();

        if (fStart != null) {
            connectStart(fStart);
        }
        if (fEnd != null) {
            connectEnd(fEnd);
        }
    }
}