/*
 * Copyright 2020-2021 MicroEJ Corp. All rights reserved.
 * This library is provided in source code for use, modification and test, subject to license terms.
 * Any modification of the source code will break MicroEJ Corp. warranties on the whole library.
 */
package ej.mwt.style.dimension;

import ej.mwt.Widget;
import ej.mwt.style.Style;
import ej.mwt.util.Alignment;
import ej.mwt.util.Rectangle;

/**
 * Helps the dimensions to lay out a widget with a specific size.
 */
public class DimensionHelper {

    /**
     * Lays out a widget.
     * <p>
     * The widget is aligned (according to the style settings) in the given area.
     *
     * @param widget
     *            the widget.
     * @param bounds
     *            the bounds.
     * @param useFixedWidth
     *            <code>true</code> to use the given fixed width instead of the given width, <code>false</code>
     *            otherwise.
     * @param useFixedHeight
     *            <code>true</code> to use the given fixed height instead of the given height, <code>false</code>
     *            otherwise.
     * @param fixedWidth
     *            the fixed width.
     * @param fixedHeight
     *            the fixed height.
     */
    public static void layOut(Widget widget, Rectangle bounds, boolean useFixedWidth, boolean useFixedHeight, int fixedWidth, int fixedHeight) {
        Style style = widget.getStyle();
        int x = bounds.getX();
        int y = bounds.getY();
        int width = bounds.getWidth();
        int height = bounds.getHeight();
        // apply optimal size
        int newWidth;
        int newHeight;
        if (useFixedWidth && fixedWidth < width) {
            newWidth = fixedWidth;
        } else {
            newWidth = width;
        }
        if (useFixedHeight && fixedHeight < height) {
            newHeight = fixedHeight;
        } else {
            newHeight = height;
        }
        // re-align
        int newX = Alignment.computeLeftX(newWidth, x, width, style.getHorizontalAlignment());
        int newY = Alignment.computeTopY(newHeight, y, height, style.getVerticalAlignment());
        bounds.setBounds(newX, newY, newWidth, newHeight);
    }
}
