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

import java.util.List;

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

import gov.va.vinci.dart.biz.Review;
import gov.va.vinci.dart.db.ReviewDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

public class ReviewDAOImpl extends HibernateDAO implements ReviewDAO {

	@Override
	public Review findById(final int reviewId) {	//throws ObjectNotFoundException {
		Query q = createQuery("from Review where id=:rid");
		q.setParameter("rid", reviewId);
		
		Review result = null;
		try {
			result = (Review)q.getSingleResult();

//			if( result == null ) {
//				throw new ObjectNotFoundException("No Review found with id " + reviewId);
//			}

		} catch (NoResultException e) {
			//throw new ObjectNotFoundException("No Review found with id " + reviewId, e);
		}
		
		return result;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listAll() {
		Query query = createQuery("from Review");
		return (List<Review>)query.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listByRequestId(final int requestId) {
		Query query = createQuery("from Review where request.id=:rid");
		query.setParameter("rid", requestId);

		return (List<Review>)query.getResultList();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listByRequestIdAndWorkflowId(final int requestId, final int workflowId) {
		Query query = createQuery("from Review where request.id=:rid and (workflow is not null and workflow.id=:wid)");
		query.setParameter("rid", requestId);
		query.setParameter("wid", workflowId);
		
		return (List<Review>)query.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listByWorkflowId(final int workflowId) {
		Query query = createQuery("from Review where (workflow is not null and workflow.id=:wid)");
		query.setParameter("wid", workflowId);
		
		return (List<Review>)query.getResultList();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listByGroupId(final int groupId) {
		Query query = createQuery("from Review where groupid=:gid");
		query.setParameter("gid", groupId);

		return (List<Review>)query.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Review> listByRequestIdAndGroupId(final int requestId, final int groupId) {
		Query query = createQuery("from Review where request.id=:rid and reviewer.id=:gid");
		query.setParameter("rid", requestId);
		query.setParameter("gid", groupId);
		
		return (List<Review>)query.getResultList();
	}
	
	@Override
	public void save(Review review) {
		if (review == null) {
			throw new IllegalArgumentException();
		}
		
		HibernateDAO.save(review);
	}

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

}
