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

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NullIfEmptyObjectEditor extends PropertyEditorSupport {
	Log log = LogFactory.getLog(NullIfEmptyObjectEditor.class);

	private Object content;

	/**
	 * 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.
	 */
	public NullIfEmptyObjectEditor() {
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	@Override
	public String getAsText() {
		if (content == null) {
			return "";
		}
		return content.toString();
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.isEmpty(text)) {
			content = null;
		} else {
			content = text;
		}
	}

	@Override
	public void setValue(Object value) {
		content = value;
	}

	@Override
	public Object getValue() {
		return content;
	}

}
