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

package CH.ifa.draw.standard;

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

import CH.ifa.draw.util.Geom;
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.StorableInput;
import de.renew.draw.storables.ontology.StorableOutput;

/**
 * AbstractConnector provides default implementation for
 * the Connector interface.
 * @see Connector
 */
public abstract class AbstractConnector implements Connector {
    /*
     * Serialization support.
     */
    @Serial
    private static final long serialVersionUID = -5170007865562687545L;
    private final int _abstractConnectorSerializedDataVersion = 1;

    /**
     * the owner of the connector
     */
    private Figure _owner;

    /**
     * Constructs a connector that has no owner. It is only
     * used internally to resurrect a connectors from a
     * StorableOutput. It should never be called directly.
     */
    public AbstractConnector() {
        _owner = null;
    }

    /**
     * Constructs a connector with the given owner figure.
     */
    public AbstractConnector(Figure owner) {
        _owner = owner;
    }

    /**
     * Gets the connector's owner.
     */
    @Override
    public Figure owner() {
        return _owner;
    }

    @Override
    public Point findStart(ConnectionFigure connection) {
        return findPoint(connection);
    }

    @Override
    public Point findEnd(ConnectionFigure connection) {
        return findPoint(connection);
    }

    /**
     * Gets the connection point. Override when the connector
     * does not need to distinguish between the start and end
     * point of a connection.
     * @param connection UNUSED
     */
    protected Point findPoint(ConnectionFigure connection) {
        return Geom.center(displayBox());
    }

    /**
     * Gets the display box of the connector.
     */
    @Override
    public Rectangle displayBox() {
        return owner().displayBox();
    }

    /**
     * Tests if a point is contained in the connector.
     */
    @Override
    public boolean containsPoint(int x, int y) {
        return owner().containsPoint(x, y);
    }

    /**
     * Draws this connector. By default, connectors are invisible.
     */
    @Override
    public void draw(Graphics g) {
        // invisible by default
    }

    /**
     * Stores the connector and its owner to a StorableOutput.
     */
    @Override
    public void write(StorableOutput dw) {
        dw.writeStorable(_owner);
    }

    /**
     * Reads the connector and its owner from a StorableInput.
     */
    @Override
    public void read(StorableInput dr) throws IOException {
        _owner = (Figure) dr.readStorable();
    }
}