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

import gov.va.vinci.dart.biz.Task;
import gov.va.vinci.dart.db.TaskDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

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

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

public class TaskDAOImpl extends HibernateDAO implements TaskDAO {

	public Task findById(final int taskId) {
//		return (Task)findById(Task.class, requestId);
		Query query = createQuery("from Task where id=:oid");
		query.setParameter("oid", taskId);
		return (Task) query.getSingleResult();		
	}

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

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


	@SuppressWarnings("unchecked")
	public List<Task> listOpenByRequestId(final int requestId) {
		Query query = createQuery("from Task where request.id=:rid and completedOn is null");	//not yet completed
		query.setParameter("rid", requestId);
		return (List<Task>)query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Task> listAll() {
		Query query = createQuery("from Task");

		try {
			return (List<Task>)query.getResultList();
		} catch (NoResultException e) {
			return new ArrayList<Task>();
		}
	}

	@Override
	public void save(Task task) {
		if (task == null) {
			throw new IllegalArgumentException();
		}

		HibernateDAO.save(task);
	}

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