/*
 * Copyright 2015-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.font;

import ej.microui.display.Font;

/**
 * Returns the font which matches exactly the font parameters.
 * <p>
 * A font matches if:
 * <ul>
 * <li>its descriptor starts with the requested family,</li>
 * <li>its height is the same as the height resolved using the requested size,</li>
 * <li>its style is the same as the requested style.</li>
 * </ul>
 */
public class StrictFontLoader {

	private final Font[] allFonts;

	/**
	 * Creates a strict font loader.
	 */
	public StrictFontLoader() {
		this.allFonts = Font.getAllFonts();
	}

	/**
	 * Gets the MicroUI font matching the given parameters.
	 *
	 * @param family
	 *            the font family.
	 * @param size
	 *            the font size.
	 * @param style
	 *            the font style.
	 * @return the font matching the given parameters.
	 */
	public Font getFont(String family, int size, int style) {
		if (size < 0) {
			throw new IllegalArgumentException();
		}

		int height = getFontHeight(size);

		for (Font font : this.allFonts) {
			String fontName = font.getDescriptor();
			if (fontName.startsWith(family) && font.getHeight() == height && font.getStyle() == style) {
				return font;
			}
		}

		// No font matches the given parameters.
		return Font.getDefaultFont();
	}

	/**
	 * Gets the MicroUI font matching the given parameters and with the plain style.
	 *
	 * @param family
	 *            the font family.
	 * @param size
	 *            the font size.
	 * @return the font matching the given parameters.
	 */
	public Font getFont(String family, int size) {
		return getFont(family, size, Font.STYLE_PLAIN);
	}

	/**
	 * Gets the expected font height in pixels for the given size.
	 * <p>
	 * This method may be overridden in order to interpret the size parameter in an other way.
	 *
	 * @param size
	 *            the font size.
	 * @return the font height.
	 */
	protected int getFontHeight(int size) {
		return size;
	}
}
