/*
 * Copyright 2015-2025 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.annotation.Nullable;
import ej.mwt.stylesheet.selector.StateSelector;
import ej.widget.event.ClickEventHandler;
import ej.widget.event.Clickable;

/**
 * An image button is a widget that displays an image and reacts to click events.
 */
public class ImageButton extends ImageWidget implements Clickable {

	/**
	 * Active state.
	 *
	 * @deprecated <code>StateSelector.ACTIVE</code> is better suited
	 */
	@Deprecated
	public static final int ACTIVE = StateSelector.ACTIVE;

	private final ClickEventHandler eventHandler;
	private boolean pressed;

	/**
	 * Creates an image button with the resource path of the image to display.
	 *
	 * @param imagePath
	 *            the resource path of the image to display.
	 */
	public ImageButton(String imagePath) {
		super(imagePath, true);

		this.eventHandler = new ClickEventHandler(this, this);
		this.pressed = false;
	}

	/**
	 * Sets the listener on the click events of this button.
	 *
	 * @param listener
	 *            the listener to set.
	 */
	public void setOnClickListener(@Nullable OnClickListener listener) {
		this.eventHandler.setOnClickListener(listener);
	}

	@Override
	public boolean isInState(int state) {
		return (state == StateSelector.ACTIVE && this.pressed) || super.isInState(state);
	}

	@Override
	public boolean handleEvent(int event) {
		return this.eventHandler.handleEvent(event);
	}

	@Override
	public void setPressed(boolean pressed) {
		this.pressed = pressed;
		updateStyle();
		requestRender();
	}

	/**
	 * Handles a click event.
	 *
	 * @deprecated Internal API.
	 */
	@Deprecated
	public void handleClick() {
		this.eventHandler.handleClick();
	}
}
