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

import java.util.ArrayList;
import java.util.List;

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

import gov.va.vinci.dart.biz.RequestParticipantDocument;
import gov.va.vinci.dart.db.RequestParticipantDocumentDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

public class RequestParticipantDocumentDAOImpl extends HibernateDAO implements RequestParticipantDocumentDAO {

	@Override
	@SuppressWarnings("unchecked")
	public List<RequestParticipantDocument> listByRequestId(final int requestId) {
		Query q = createQuery("from RequestParticipantDocument where requestId=:rid");
		q.setParameter("rid",requestId);
		try {
			return (List<RequestParticipantDocument>) q.getResultList();
		} catch (NoResultException e) {
			// whatever - give me an empty result then.
			return new ArrayList<RequestParticipantDocument>();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<RequestParticipantDocument> listByDocumentId(final int documentId) {
		Query q = createQuery("from RequestParticipantDocument where documentId=:did");
		q.setParameter("did", documentId);
		try {
			return (List<RequestParticipantDocument>) q.getResultList();
		} catch (NoResultException e) {
			// whatever - give me an empty result then.
			return new ArrayList<RequestParticipantDocument>();
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<RequestParticipantDocument> listByRequestAndParticipantId(final int requestId, final int participantId) {
		Query q = createQuery("from RequestParticipantDocument where requestId=:rid and participantId=:pid");
		q.setParameter("rid",requestId);
		q.setParameter("pid",participantId);
		try {
			return (List<RequestParticipantDocument>) q.getResultList();
		} catch (NoResultException e) {
			// whatever - give me an empty result then.
			return new ArrayList<RequestParticipantDocument>();
		}
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<RequestParticipantDocument> listActiveDocsByRequestAndParticipantId(final int requestId, final int participantId) {
		Query q = createQuery("from RequestParticipantDocument where requestId=:rid and participantId=:pid and active=true");
		q.setParameter("rid",requestId);
		q.setParameter("pid",participantId);
		try {
			return (List<RequestParticipantDocument>) q.getResultList();
		} catch (NoResultException e) {
			// whatever - give me an empty result then.
			return new ArrayList<RequestParticipantDocument>();
		}
	}


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

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