/**
 *  Licensed under GPL. For more information, see
 *    http://jaxodraw.sourceforge.net/license.html
 *  or the LICENSE file in the jaxodraw distribution.
 */
package net.sf.jaxodraw.object.vertex;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

import java.io.IOException;
import java.io.ObjectInputStream;

import net.sf.jaxodraw.object.JaxoObject;
import net.sf.jaxodraw.object.JaxoObjectEditPanel;
import net.sf.jaxodraw.util.JaxoColor;
import net.sf.jaxodraw.util.graphics.JaxoGraphics2D;


/** A vertex (a filled square).
 * @since 2.0
 */
public class JaxoVertexT3 extends JaxoVertex {
    private static final long serialVersionUID = 314159L;
    private transient Rectangle2D square = new Rectangle2D.Float();

    private void readObject(final ObjectInputStream in)
        throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        square = new Rectangle2D.Float();
    }

    /** {@inheritDoc} */
    @Override
    public final boolean isCopy(final JaxoObject comp) {
        boolean isCopy = false;
        if (comp instanceof JaxoVertexT3) {
            isCopy = super.isCopy(comp);
        }

        return isCopy;

    }

    /** {@inheritDoc} */
    public final void paint(final JaxoGraphics2D g2) {
        updateSquare();

        g2.setColor(getColor());

        g2.fill(square);
        g2.draw(square);
    }

    /**
     * Returns the bounding box of this object.
     *
     * @return the bounding box of this object.
     */
    public Rectangle getBounds() {
        updateSquare();

        return getStroke().createStrokedShape(square).getBounds();
    }

    /** {@inheritDoc} */
    public final String latexCommand(final float scale, final Dimension canvasDim) {
        final float radius = getLaTexRadius(scale);

        if ((int) radius == 0) {
            return "%";
        }

        final Point2D center = getLaTexCenter(scale, canvasDim.height);

        final float xi = (float) center.getX() - radius;
        final float yi = (float) center.getY() + radius;
        final float xf = (float) center.getX() + radius;
        final float yf = (float) center.getY() - radius;

        final String tlc = JaxoColor.getColorName(getColor());

        return "\\CBox" + "(" + D_FORMAT.format(xf) + ","
            + D_FORMAT.format(yf) + ")" + "(" + D_FORMAT.format(xi) + ","
            + D_FORMAT.format(yi) + ")" + "{" + tlc + "}" + "{" + tlc
            + "}" + "%%JaxoDrawID:Vertex";
    }

    /** {@inheritDoc} */
    public void prepareEditPanel(final JaxoObjectEditPanel editPanel) {
        prepareGenericPanel(editPanel, "vertexT3.png");
    }

    private void updateSquare() {
        final double length =
            Math.sqrt((getWidth() * getWidth()) + (getHeight() * getHeight()));

        square.setFrame(-length + getX(), -length + getY(), 2 * length,
            2 * length);
    }
}
