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

import gov.va.vinci.dart.common.exception.ObjectNotFoundException;
import gov.va.vinci.dart.biz.Participant;
import gov.va.vinci.dart.db.ParticipantDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ParticipantDAOImpl extends HibernateDAO implements ParticipantDAO {
	private static Log log = LogFactory.getLog(ParticipantDAOImpl.class);

	@Override
	public Participant findById(final int participantId) {
		Query query = createQuery("from Participant where id=:pid");
		query.setParameter("pid", participantId);
		
		Participant p = null;
		try {
			p = (Participant)query.getSingleResult();
		} catch( Exception e ) {
			log.error("Exception retrieving participantId:  " + participantId);
			//log.error( e.getStackTrace() );
		}
		
		return p;
	}
	
	@Override
	public Participant find(final int requestId, final int personId, final int locationId) {
		
		Query query = createQuery("from Participant where request.id=:rid and person.id=:pid and location.id=:lid");
		query.setParameter("rid", requestId);
		query.setParameter("pid", personId);
		query.setParameter("lid", locationId);
		return (Participant)query.getSingleResult();
	}
	
	@Override
	public Participant findPrincipalInvestigator(final int requestId, final int locationId) throws ObjectNotFoundException {

		try {
			Query query = createQuery("from Participant p where request.id=:rid and principalInvestigator=1 and p.location.id=:lid");
			query.setParameter("rid", requestId);
			query.setParameter("lid", locationId);
			return (Participant)query.getSingleResult();
		} catch (NoResultException e) {
			throw new ObjectNotFoundException("No principal investigator found for request " + requestId, e);
		}
		
	}

	@Override
	public void save(Participant participant) {
		if (participant == null) {
			throw new IllegalArgumentException();
		}
		
		HibernateDAO.save(participant);
	}

	@Override
	public void delete(Participant participant) {
		if (participant == null) {
			throw new IllegalArgumentException();
		}
		
		HibernateDAO.delete(participant);
	}	
		

}
