/*
 * Copyright 2020-2024 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.annotation.Nullable;
import ej.mwt.Widget;
import ej.mwt.util.Rectangle;
import ej.mwt.util.Size;

/**
 * Dimension which fits the optimal size of the widget.
 */
public class OptimalDimension implements Dimension {

	/**
	 * Optimal dimension using widget's optimal width and height.
	 */
	public static final OptimalDimension OPTIMAL_DIMENSION_XY = new OptimalDimension(true, true);
	/**
	 * Optimal dimension using widget's optimal width.
	 */
	public static final OptimalDimension OPTIMAL_DIMENSION_X = new OptimalDimension(true, false);
	/**
	 * Optimal dimension using widget's optimal height.
	 */
	public static final OptimalDimension OPTIMAL_DIMENSION_Y = new OptimalDimension(false, true);

	private final boolean useOptimalWidth;
	private final boolean useOptimalHeight;

	private OptimalDimension(boolean useOptimalWidth, boolean useOptimalHeight) {
		this.useOptimalWidth = useOptimalWidth;
		this.useOptimalHeight = useOptimalHeight;
	}

	@Override
	public void getAvailableSize(Widget widget, int availableWidth, int availableHeight, Size availableSize) {
		// Nothing to do.
	}

	@Override
	public void computeOptimalSize(Widget widget, int availableWidth, int availableHeight, Size optimalSize) {
		// Nothing to do.
	}

	@Override
	public void layOut(Widget widget, Rectangle bounds) {
		DimensionHelper.layOut(widget, bounds, this.useOptimalWidth, this.useOptimalHeight, widget.getWidth(),
				widget.getHeight());
	}

	@Override
	public boolean equals(@Nullable Object obj) {
		if (obj != null && getClass() == obj.getClass()) {
			OptimalDimension dimension = (OptimalDimension) obj;
			return (this.useOptimalWidth == dimension.useOptimalWidth
					&& this.useOptimalHeight == dimension.useOptimalHeight);
		}
		return false;
	}

	@Override
	public int hashCode() {
		return (this.useOptimalWidth ? 1 : 0) | (this.useOptimalHeight ? 2 : 0);
	}
}
