package lu.tudor.santec.gecamed.letter.gui.placeholders;

import java.util.Collection;
import java.util.List;

import lu.tudor.santec.gecamed.core.utils.ManagerFactory;
import lu.tudor.santec.gecamed.core.utils.NamedParameterBean;
import lu.tudor.santec.gecamed.letter.ejb.session.beans.LetterPlaceholderBean;
import lu.tudor.santec.gecamed.letter.ejb.session.interfaces.LetterPlaceholderInterface;

public class DatabaseManager
{
	/* ======================================== */
	// 		MEMBERS
	/* ======================================== */
	
	private static LetterPlaceholderInterface	manager;
	
	
	
	/* ======================================== */
	// 		CLASS BODY
	/* ======================================== */

	public NamedParameterBean createParameter (String name, Object value)
	{
		return new NamedParameterBean(name, value);
	}
	
	
	/* ---------------------------------------- */
	// 		HQL query methods
	/* ---------------------------------------- */
	
	public List<?> doHqlQuery (String query, Integer firstResult, Integer maxResult, Collection<?> parameters)
	{
		return getManager().doHqlQuery(query, firstResult, maxResult, 
				parameters == null ? null : parameters.toArray());
	}
	
	
	public List<?> doHqlQuery (String query, Integer firstResult, int maxResult)
	{
		return doHqlQuery(query, firstResult, maxResult, null);
	}
	
	
	public List<?> doHqlQuery (String query, Collection<?> parameters)
	{
		return doHqlQuery(query, null, null, parameters);
	}
	
	
	public List<?> doHqlQuery (String query)
	{
		return doHqlQuery(query, null);
	}
	
	
	public Object getHqlQueryObject (String query, Collection<?> parameters)
	{
		List<?>	result	= doHqlQuery(query, null, null, parameters);
		
		
		if (result == null || result.isEmpty())
			 return null;
		else return result.get(0);
	}
	
	
	public Object getHqlQueryObject (String query)
	{
		return getHqlQueryObject(query, null);
	}
	
	
	/* ---------------------------------------- */
	// 		Native query methods
	/* ---------------------------------------- */
	
	public List<?> doNativeQuery (String query, Collection<?> parameters)
	{
		return getManager().doNativeQuery(query, 
				parameters == null ? null : parameters.toArray());
	}
	
	
	public List<?> doNativeQuery (String query)
	{
		return doNativeQuery(query, null);
	}
	
	
	public Object getNativeQueryObject (String query, Collection<?> parameters)
	{
		List<?>	result	= getManager().doNativeQuery(query, parameters);
		
		
		if (result == null || result.isEmpty())
			 return null;
		else return result.get(0);
	}
	
	
	public Object getNativeQueryObject (String query)
	{
		return getNativeQueryObject(query, null);
	}
	
	
	
	/* ======================================== */
	// 		HELP METHODS
	/* ======================================== */
	
	private LetterPlaceholderInterface getManager ()
	{
		if (manager == null)
			manager	= (LetterPlaceholderInterface) ManagerFactory
					.getRemote(LetterPlaceholderBean.class);
		
		return manager;
	}
}
