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

package CH.ifa.draw.standard;

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

import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.Locator;
import de.renew.draw.storables.ontology.StorableInput;
import de.renew.draw.storables.ontology.StorableOutput;

/**
 * A locator that specifies a point that is relative to the bounds
 * of a figure.
 * @see Locator
 */
public class RelativeLocator extends AbstractLocator {
    /*
     * Serialization support.
     */
    @Serial
    private static final long serialVersionUID = 2619148876087898602L;
    private final int _relativeLocatorSerializedDataVersion = 1;

    double _relativeX;
    double _relativeY;

    public RelativeLocator() {
        _relativeX = 0.0;
        _relativeY = 0.0;
    }

    public RelativeLocator(double relativeX, double relativeY) {
        _relativeX = relativeX;
        _relativeY = relativeY;
    }

    @Override
    public Point locate(Figure owner) {
        Rectangle r = owner.displayBox();
        return new Point(r.x + (int) (r.width * _relativeX), r.y + (int) (r.height * _relativeY));
    }

    @Override
    public void write(StorableOutput dw) {
        super.write(dw);
        dw.writeDouble(_relativeX);
        dw.writeDouble(_relativeY);
    }

    @Override
    public void read(StorableInput dr) throws IOException {
        super.read(dr);
        _relativeX = dr.readDouble();
        _relativeY = dr.readDouble();
    }

    static public Locator east() {
        return new RelativeLocator(1.0, 0.5);
    }

    /**
     * North.
     */
    static public Locator north() {
        return new RelativeLocator(0.5, 0.0);
    }

    /**
     * West.
     */
    static public Locator west() {
        return new RelativeLocator(0.0, 0.5);
    }

    /**
     * North-east.
     */
    static public Locator northEast() {
        return new RelativeLocator(1.0, 0.0);
    }

    /**
     * North-west.
     */
    static public Locator northWest() {
        return new RelativeLocator(0.0, 0.0);
    }

    /**
     * South.
     */
    static public Locator south() {
        return new RelativeLocator(0.5, 1.0);
    }

    /**
     * South-east.
     */
    static public Locator southEast() {
        return new RelativeLocator(1.0, 1.0);
    }

    /**
     * South-west.
     */
    static public Locator southWest() {
        return new RelativeLocator(0.0, 1.0);
    }

    /**
     * Center.
     */
    static public Locator center() {
        return new RelativeLocator(0.5, 0.5);
    }
}