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

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

import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.model.GeocodingResult;
import com.vividsolutions.jts.geom.Point;

public class GoogleGeocoder implements it.mice.voila.runtime.hibernatespatial.utils.Geocoder {
	private static Log logger = LogFactory.getLog(GoogleGeocoder.class);

    private String apiKey;

	@Override
	public String getApiKey() {
		return apiKey;
	}

	public void setApiKey(String apiKey) {
		this.apiKey = apiKey;
	}

	public Point geocode(String address) {
		logger.info("Start geocoding address:" + address);

		GeoApiContext context = new GeoApiContext.Builder().apiKey(getApiKey()).build();
		GeocodingResult[] results;
		Point result = null;
		try {
			results = GeocodingApi.geocode(context, address).await();
			double lat = results[0].geometry.location.lat;
			double lng = results[0].geometry.location.lng;
			String geometryAsString = "POINT(" + lat + " " + lng + ")";
			result = (Point) GisConvertUtils.toGeometry(geometryAsString);
			logger.info("End geocoding address:" + address + ", result:" + result);
			return result;
		} catch (Exception e) {
			if (logger.isErrorEnabled()) {
				logger.error("Problem geocoding address: " + address, e);
			}
			return null;
		}
	}
}
