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

import ej.microui.display.Font;
import ej.microui.display.GraphicsContext;
import ej.mwt.Widget;
import ej.mwt.style.Style;
import ej.mwt.util.Size;
import ej.widget.render.StringPainter;

/**
 * A label is a widget that displays a text.
 * <p>
 * This example shows a simple label:
 *
 * <pre>
 * Label label = new Label("Hello World");
 * </pre>
 *
 * <img src="doc-files/label-simple.png" alt="Simple label.">
 * <p>
 * This example shows a styled label:
 *
 * <pre>
 * Label label = new Label("Hello World");
 *
 * CascadingStylesheet stylesheet = new CascadingStylesheet();
 * desktop.setStylesheet(stylesheet);
 *
 * EditableStyle labelStyle = stylesheet.getSelectorStyle(new TypeSelector(Label.class));
 * labelStyle.setColor(Colors.NAVY);
 * labelStyle.setBackground(new RectangularBackground(Colors.CYAN));
 * labelStyle.setFont(Font.getFont("/fonts/source_sans_pro_24.ejf"));
 * </pre>
 *
 * <img src="doc-files/label-styled.png" alt="Styled label.">
 */
public class Label extends Widget {

	private String text;

	/**
	 * Creates a label with an empty text.
	 */
	public Label() {
		this("");
	}

	/**
	 * Creates a label with the given text to display.
	 *
	 * @param text
	 *            the text to display.
	 */
	public Label(String text) {
		this.text = text;
	}

	/**
	 * Creates a label with the given text to display and its enabled state.
	 *
	 * @param text
	 *            the text to display.
	 * @param enabled
	 *            <code>true</code> if this label is to be enabled, <code>false</code> otherwise.
	 */
	protected Label(String text, boolean enabled) {
		super(enabled);
		this.text = text;
	}

	/**
	 * Gets the text displayed on this label.
	 *
	 * @return the text displayed on this label.
	 */
	public String getText() {
		return this.text;
	}

	/**
	 * Sets the text to display on this label.
	 *
	 * @param text
	 *            the text to display on this label.
	 */
	public void setText(String text) {
		this.text = text;
	}

	@Override
	protected void renderContent(GraphicsContext g, int contentWidth, int contentHeight) {
		Style style = getStyle();
		g.setColor(style.getColor());
		StringPainter.drawStringInArea(g, this.text, style.getFont(), 0, 0, contentWidth, contentHeight,
				style.getHorizontalAlignment(), style.getVerticalAlignment());
	}

	@Override
	protected void computeContentOptimalSize(Size size) {
		Font font = getStyle().getFont();
		StringPainter.computeOptimalSize(this.text, font, size);
	}
}
