package it.mice.voila.runtime.hibernatespatial.utils;

import it.mice.voila.runtime.hibernatespatial.JsonPoint;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.io.WKTWriter;

public class GisConvertUtils {
	public static final int SRID = 4326;

	public static String toString(Geometry point) {
		if (point == null) {
			return null;
		}
		WKTWriter writer = new WKTWriter();
		String result = writer.write(point);
		return result;
	}

	public static Geometry toGeometry(String value) {
		if (value == null || "null".equals(value)) {
			return null;
		}
		WKTReader reader = new WKTReader();
		Geometry result = null;
		try {
			result = reader.read(value);
			result.setSRID(SRID);
		} catch (ParseException e) {
			throw new RuntimeException("Not a WKT string:" + value);
		}
		return result;
	}

	public static String toPointString(JsonPoint point) {
		if (point == null) {
			return null;
		}
		return toPointString(point.getLatitude(), point.getLongitude());
	}

	public static String toPointString(Object latitude, Object longitude) {
		return "POINT(" + latitude + " " + longitude + ")";
	}

	public static Geometry toGeometry(Object latitude, Object longitude) {
		return toGeometry(toPointString(latitude, longitude));
	}
}
