package de.renew.gui;

import java.awt.Dimension;
import java.awt.Point;

import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.FigureEnumeration;

/**
 * A Figure that is composed of several figures placed side by side.
 */
public class HorizontalCompositeFigure extends SimpleCompositeFigure {

    /**
     * Pass-through-constructor for subclasses. Does nothing.
     **/
    protected HorizontalCompositeFigure() {}

    /**
     * Creates a new composite figure with one contained
     * figure. The composite figure is layouted immediately after
     * creation. Additional figures can be added at later times.
     * @param fig The figure, which is used for initialization
     */
    public HorizontalCompositeFigure(Figure fig) {
        add(fig);
        layout();
    }

    /**
     * Calculates the locations of the individual figures contained
     * in the composite figure and updates them on their location.
     */
    @Override
    protected void layout() {
        Dimension extent = calcExtent();
        fDisplayBox.width = extent.width;
        fDisplayBox.height = extent.height;

        FigureEnumeration figenumeration = figures();
        Point location = fDisplayBox.getLocation();
        while (figenumeration.hasMoreElements()) {
            Figure figure = figenumeration.nextElement();
            Dimension figureDim = figure.size();
            location.y = fDisplayBox.y + Math.max(0, (fDisplayBox.height - figureDim.height) / 2);
            Point corner = new Point(location.x + figureDim.width, location.y + figureDim.height);
            figure.basicDisplayBox(location, corner);
            location.x += figureDim.width;
        }
        super.layout();
    }

    /**
     * Recalculates the size for the figure and checks
     * whether it still matches the current layout.
     *
     * @return whether the layout needs to be changed
     */
    @Override
    protected boolean needsLayout() {
        return !size().equals(calcExtent());
    }

    /**
     * Calculates the size of the figure by adding up the widths
     * of all contained figures and taking the maximum height.
     *
     * @return the final size of the figure
     */
    private Dimension calcExtent() {
        FigureEnumeration figenumeration = figures();
        Dimension extent = new Dimension(0, 0);
        while (figenumeration.hasMoreElements()) {
            Figure figure = figenumeration.nextElement();
            Dimension figureDim = figure.size();
            extent.width += figureDim.width;
            extent.height = Math.max(extent.height, figureDim.height);
        }
        return extent;
    }
}
