package com.lisasoft.routedirections.ard.beans;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.postgis.Geometry;
import org.postgis.Point;

@Stateless
public class RouteDirectionsARDBean implements RouteDirectionsARD {

	private final Logger log = Logger.getLogger(RouteDirectionsARDBean.class);

	/**
	 * This is part of the Bean Management
	 */
	@PersistenceContext
	private EntityManager manager;

	/**
	 * Default constructor for the Session Bean.
	 */
	public RouteDirectionsARDBean() {
		super();
	}

	/**
	 * 
	 */
	public Location getLocation(String name) {
		final String QUERY_STR = "select location from Location as location where location.name = :nameToken";
		Location retLocation = null;
		try {
			final Query query = manager.createQuery(QUERY_STR);
			query.setParameter("nameToken", name);
			retLocation = (Location) query.getSingleResult();
		} catch (Exception e) {
			log.error("Problem with Hibernate SQL: ", e);
		}
		return retLocation;
	}

	/**
	 * save a location
	 * @param loc
	 * @return 
	 */
	public boolean setLocation(final Location loc) {
		
		boolean retBoolean = false;

		try {
			//NATIVE SQL QUERY
			//final String INSERT_STR = "INSERT INTO Location (id, name, geom) values (nextval('hibernate_sequence'), '"+loc.getName()+"',  "+this.getTheGeomFromText(loc.getGeom())+")";
			//final String INSERT_STR = "INSERT INTO Location (id, name) values (nextval('hibernate_sequence'), '"+loc.getName()+"')";
			//Query query = manager.createNativeQuery(INSERT_STR);
			//int result = query.executeUpdate();
			//log.debug("Number of Locations INSERTED in table: "+result);
			
			//HIBERNATE MANAGED MERGE
			manager.persist(loc);
			manager.flush();
			//manager.merge(loc); //need to use native query!
			retBoolean = true;

		} catch (Exception e) {
			log.error("Problem with Hibernate SQL: ", e);
		}
		return retBoolean;
	}
	
	
	private String getTheGeomFromText(Geometry geometry) {
		String returnVal = "null";
		if (geometry instanceof Point) {
			Point point = (Point) geometry;
			returnVal = "GeomFromText('POINT("+point.getX()+" "+point.getY()+")',4283)";
		}
		return returnVal;
	}
}