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

import it.mice.voila.runtime.hibernatespatial.utils.GisConvertUtils;

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;

import com.vividsolutions.jts.geom.Geometry;

public class GeometryEditor extends PropertyEditorSupport {
	private final boolean allowEmpty;

	Log log = LogFactory.getLog(GeometryEditor.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 GeometryEditor(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(GisConvertUtils.toGeometry(text));
			} catch (Exception ex) {
				throw new IllegalArgumentException("Could not parse geometry text value to a valid Geometry: " + ex.getMessage(), ex);
			}
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		if (getValue() == null) {
			return "";
		}
		return GisConvertUtils.toString((Geometry)getValue());
	}

}
