/*
 * 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.render;

import ej.microui.display.Font;
import ej.microui.display.GraphicsContext;
import ej.microui.display.Painter;
import ej.mwt.util.Alignment;
import ej.mwt.util.Size;

/**
 * Provides utility methods to draw strings.
 */
public class StringPainter {

	// Prevents initialization.
	private StringPainter() {
	}

	/**
	 * Computes the optimal size of a string.
	 * <p>
	 * The given size is modified to set the optimal size.
	 *
	 * @param string
	 *            the string.
	 * @param font
	 *            the font.
	 * @param size
	 *            the size to modify.
	 */
	public static void computeOptimalSize(String string, Font font, Size size) {
		int width = font.stringWidth(string);
		int height = font.getHeight();
		size.setSize(width, height);
	}

	/**
	 * Draws a string aligned in a area.
	 *
	 * @param g
	 *            the graphics context.
	 * @param string
	 *            the string.
	 * @param font
	 *            the font.
	 * @param x
	 *            the area x coordinate.
	 * @param y
	 *            the area y coordinate.
	 * @param width
	 *            the area width.
	 * @param height
	 *            the area height.
	 * @param horizontalAlignment
	 *            the horizontal alignment.
	 * @param verticalAlignment
	 *            the vertical alignment.
	 */
	public static void drawStringInArea(GraphicsContext g, String string, Font font, int x, int y, int width,
			int height, int horizontalAlignment, int verticalAlignment) {
		int stringX = Alignment.computeLeftX(font.stringWidth(string), x, width, horizontalAlignment);
		int stringY = Alignment.computeTopY(font.getHeight(), y, height, verticalAlignment);
		Painter.drawString(g, string, font, stringX, stringY);
	}

	/**
	 * Draws a string aligned with an anchor point.
	 *
	 * @param g
	 *            the graphics context.
	 * @param string
	 *            the string.
	 * @param font
	 *            the font.
	 * @param anchorX
	 *            the anchor point x coordinate.
	 * @param anchorY
	 *            the anchor point y coordinate.
	 * @param horizontalAlignment
	 *            the horizontal alignment.
	 * @param verticalAlignment
	 *            the vertical alignment.
	 */
	public static void drawStringAtPoint(GraphicsContext g, String string, Font font, int anchorX, int anchorY,
			int horizontalAlignment, int verticalAlignment) {
		int x = Alignment.computeLeftX(font.stringWidth(string), anchorX, horizontalAlignment);
		int y = Alignment.computeTopY(font.getHeight(), anchorY, verticalAlignment);
		Painter.drawString(g, string, font, x, y);
	}
}
