/*
 * This file is a part of EpnTAPClient.
 * This program aims to provide EPN-TAP support for software clients, like CASSIS spectrum analyzer.
 * See draft specifications: https://voparis-confluence.obspm.fr/pages/viewpage.action?pageId=559861
 * Copyright (C) 2016 Institut de Recherche en Astrophysique et Planétologie.
 *
 * This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or (at your option) any later
 * version. This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE. See the GNU General Public License for more details. You should have received a copy of
 * the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package eu.omp.irap.vespa.epntapclient.gui.requestpanel.paramfield;

import java.awt.Color;

import javax.swing.JTextField;

import eu.omp.irap.vespa.epntapclient.gui.requestpanel.RequestPanelListener;

/**
 * The float field is used for parameter with a `Float` class. It is a JTextField which checks if
 * the content is a valid float. If the parameter is valid or if it is empty, then the float value
 * is sent to the controller.
 *
 * @author N. Jourdane
 */
public class FloatField extends ParamField implements TextFieldListener {

	/** The serial version UID. */
	private static final long serialVersionUID = 1L;

	/** The JTextField used to put the parameter value. */
	private JTextField field;


	/**
	 * Method constructor
	 *
	 * @param requestPanelListener The listener of the request panel.
	 * @param paramName The name of the parameter.
	 */
	public FloatField(RequestPanelListener requestPanelListener, String paramName) {
		super(requestPanelListener, paramName);
		field = new JTextField();
		addChangeListener(this, field);
		this.add(field);
	}

	/**
	 * This method is called each time the field is modified.
	 */
	@Override
	public void update(JTextField textField) {
		if (textField.getText().isEmpty()) {
			textField.setBackground(Color.WHITE);
			requestPanelListener.onParameterRemoved(paramName);
		} else {
			try {
				float value = Float.parseFloat(textField.getText());
				requestPanelListener.onParameterUpdated(paramName, value);
				textField.setBackground(Color.WHITE);
			} catch (NumberFormatException e) {
				textField.setBackground(Color.PINK);
			}
		}
	}
}