/**
 * 
 */
package gov.va.med.cds.persistence.hibernate;

import java.util.Map;

import org.dom4j.Element;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;

/**
 * @author vhaislegberb
 * 
 */
public class ConfigurableNamedQueryEntityLocator implements
		HibernateEntityLocatorInterface<Element> {

	private String queryName = null;

	private Map<String, String> queryParameterMap = null; // [paramId, location.descriptor]

	@Override
	public Element find(Session session, Element unmanaged) {

		Query query = session.getNamedQuery(this.queryName);

		// initialize the parameters
		for (String paramName : queryParameterMap.keySet()) {
			String paramValue = getParameterValueFromElement(unmanaged,
					this.queryParameterMap.get(paramName));
			query.setParameter(paramName, paramValue, StandardBasicTypes.STRING);
		}

		return (Element) query.uniqueResult();
	}

	public void setQueryName(String queryName) {
		this.queryName = queryName;
	}
	
	public void setQueryParameterMap(Map<String, String> queryParameterMap) {
		this.queryParameterMap = queryParameterMap;
	}

	private String getParameterValueFromElement(Element element, String path) {

		String[] pathElements = path.split("\\.", 2);

		// regex should return at most two elements and at minimum 1 element
		if (pathElements.length == 2) {
			return getParameterValueFromElement(
					element.element(pathElements[0]), pathElements[1]);
		} else {
			return element.elementTextTrim(pathElements[0]);
		}
	}
}
