/*
 * Copyright 2020-2023 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.widget.debug;

import ej.mwt.Container;
import ej.mwt.Widget;

/**
 * Provides helpers to analyze the bounds of the widgets.
 */
public class BoundsInspector {

	private static final String ABSOLUTE = "absolute:";

	// Prevents initialization.
	private BoundsInspector() {
	}

	/**
	 * Prints the bounds of the given widget in a String.
	 * <p>
	 * Prints the class name of the widget, its bounds (relative to its parent) and its absolute position.
	 *
	 * @param widget
	 *            the widget.
	 * @return the bounds.
	 */
	public static String boundsToString(Widget widget) {
		StringBuilder builder = new StringBuilder();

		appendBounds(builder, widget);

		return builder.toString();
	}

	/**
	 * Prints the bounds of the given widget and of all its children recursively.
	 *
	 * @param widget
	 *            the widget.
	 * @return the bounds.
	 * @see #boundsToString(Widget)
	 */
	public static String boundsRecursiveToString(Widget widget) {
		StringBuilder builder = new StringBuilder();

		appendBoundsRecursive(builder, widget, 0);

		return builder.toString();
	}

	private static void appendBoundsRecursive(StringBuilder builder, Widget widget, int depth) {
		HierarchyInspector.appendDepth(builder, depth);
		appendBounds(builder, widget);
		builder.append('\n');
		if (widget instanceof Container) {
			appendChildrenBounds(builder, (Container) widget, depth);
		}
	}

	private static void appendChildrenBounds(StringBuilder builder, Container container, int depth) {
		int childrenCount = container.getChildrenCount();
		for (int i = 0; i < childrenCount; i++) {
			Widget child = container.getChild(i);
			appendBoundsRecursive(builder, child, depth + 1);
		}
	}

	private static void appendBounds(StringBuilder builder, Widget widget) {
		HierarchyInspector.appendElement(builder, widget);
		builder.append(':').append(' ');
		appendRelativePosition(builder, widget);
		builder.append(' ');
		appendSize(builder, widget);
		builder.append(' ').append('(').append(ABSOLUTE).append(' ');
		appendAbsolutePosition(builder, widget);
		builder.append(')');
	}

	private static void appendRelativePosition(StringBuilder builder, Widget widget) {
		builder.append(widget.getX()).append(',').append(widget.getY());
	}

	/* package */ static void appendSize(StringBuilder builder, Widget widget) {
		builder.append(widget.getWidth()).append('x').append(widget.getHeight());
	}

	/* package */ static void appendAbsolutePosition(StringBuilder builder, Widget widget) {
		builder.append(widget.getAbsoluteX()).append(',').append(widget.getAbsoluteY());
	}

}
