package gov.va.med.esr.common.persistent.lookup.hibernate;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import gov.va.med.esr.common.model.lookup.County;
import gov.va.med.esr.common.model.lookup.State;
import gov.va.med.esr.common.persistent.lookup.CountyDAO;
import gov.va.med.fw.persistent.DAOException;
import gov.va.med.fw.persistent.hibernate.AbstractDAOAction;
/**
 * 
 * @author Rajiv Patnaik
 * Created on Nov 4, 2005
 * @version 1.0
 * 
 * Copyright © 2005 VHA. All rights reserved
 */
public class CountyDAOImpl extends LookupsDAOImpl implements CountyDAO
{
    private static final long serialVersionUID = 6092897369012916434L;
    
    private String queryByCountyNameAndStateCode = null;
    
    /**
     * Get County by County name and State Code
     * Returns null if there is no match.
     * 
     * @return County A corresponding County by County name and state code
     */    
    public County getCountyByCountyNameAndStateCode(String countyName, String stateCode)
            throws DAOException
    {
        try
        {
    		Map contextData = new HashMap();
    		contextData.put("countyName", countyName);				
    		contextData.put("stateCode", stateCode);        		        	
    		HibernateCallback callback = new AbstractDAOAction(contextData) { 
    			public Object execute(Session session) {
    	            Query query = session.getNamedQuery(queryByCountyNameAndStateCode);

    	            // Set the filter on county
    	            query.setString("countyName", (String) getContextData().get("countyName"));
    	            query.setString("stateCode", (String) getContextData().get("stateCode"));

    	            // Use caching if enabled
    	            if (isCacheQuery())
    	            {
    	                query.setCacheable(true);
    	                query.setCacheRegion(getCacheRegion());
    	            }
    	            return query.setMaxResults(1).uniqueResult();    				
    			}
    		};
    		return (County) this.getHibernateTemplate().execute(callback);    		
        }
        catch(HibernateException e)
        {
            throw new DAOException("Failed to get State by name.", e);
        }
    }
 
    
    /**
     * @return Returns the queryByCountyNameAndStateCode.
     */
    public String getQueryByCountyNameAndStateCode()
    {
        return queryByCountyNameAndStateCode;
    }
    /**
     * @param queryByCountyNameAndStateCode The queryByCountyNameAndStateCode to set.
     */
    public void setQueryByCountyNameAndStateCode(
            String queryByCountyNameAndStateCode)
    {
        this.queryByCountyNameAndStateCode = queryByCountyNameAndStateCode;
    }
}
