package gov.va.vinci.dart.db.impl;

import gov.va.vinci.dart.common.exception.ObjectNotFoundException;
import gov.va.vinci.dart.biz.Location;
import gov.va.vinci.dart.db.LocationDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

public class LocationDAOImpl extends HibernateDAO implements LocationDAO {

	public Location findById(final int locationId)  throws ObjectNotFoundException {
		Query q = createQuery("from Location where id=:lid");
		q.setParameter("lid", locationId);
		
		try {
			Location result = (Location)q.getSingleResult();
			
			if (result == null) {
				throw new ObjectNotFoundException("Location id " + locationId + " not found.");
			}
			
			return result;
		}
		catch (NoResultException e) {
			throw new ObjectNotFoundException("Location id " + locationId + " not found.", e);
		}
		catch (NonUniqueResultException e) {
			throw new ObjectNotFoundException("Location id " + locationId + " not found.", e);
		}
	}

	public Location findByName(final String name) throws ObjectNotFoundException {
		
		Query query = createQuery("from Location where name like :lname");
		query.setParameter("lname", name);
		
		try {
			return (Location)query.getSingleResult();
		} catch (NoResultException e) {
			throw new ObjectNotFoundException("Location id " + name + " not found.", e);
		}
		catch (NonUniqueResultException e) {
			throw new ObjectNotFoundException("Location id " + name + " not found.", e);
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Location> listAll() {
		Query query = createQuery("from Location");
		return (List<Location>)query.getResultList();
	}
}
