package it.mice.voila.runtime.springmvc.editors;

import java.beans.PropertyEditorSupport;
import java.math.BigDecimal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

public class CustomBigDecimalEditor extends PropertyEditorSupport {
	private final boolean allowEmpty;

	Log log = LogFactory.getLog(CustomBigDecimalEditor.class);

	/**
	 * Create a new CustomDateEditor instance, using the given DateFormat
	 * for parsing and rendering.
	 * <p>The "allowEmpty" parameter states if an empty String should
	 * be allowed for parsing, i.e. get interpreted as null value.
	 * Otherwise, an IllegalArgumentException gets thrown in that case.
	 * @param allowEmpty if empty strings should be allowed
	 */
	public CustomBigDecimalEditor(boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (this.allowEmpty && !StringUtils.hasText(text)) {
			// Treat empty String as null value.
			setValue(null);
		} else {
			try {
				setValue(new BigDecimal(text));
			} catch (Exception ex) {
				throw new IllegalArgumentException("Could not parse numeric value to a valid BigDecimal: " + ex.getMessage(), ex);
			}
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		BigDecimal value = (BigDecimal) getValue();
		return (value != null ? value.toString().replace(".", ",") : "");
	}

}
