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

import gov.va.vinci.dart.biz.DataSource;
import gov.va.vinci.dart.db.DataSourceDAO;
import gov.va.vinci.dart.db.util.HibernateDAO;

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

import javax.persistence.Query;

public class DataSourceDAOImpl extends HibernateDAO implements DataSourceDAO {

	@Override
	public DataSource findById(final int dataSourceId) {
//		return (DataSource)findById(DataSource.class, dataSourceId);
		Query q = createQuery("from DataSource where id=:did");
		q.setParameter("did", dataSourceId);
		return (DataSource)q.getSingleResult();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<DataSource> listAll() {
		Query query = createQuery("from DataSource");
		return (List<DataSource>)query.getResultList();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<DataSource> findByDocumentTemplateId(final int documentTemplateId) {
		
		Query query = createQuery("select ds from DataSource ds join ds.documentTemplates t where t.id=:tid");
		query.setParameter("tid", documentTemplateId);
		return  (List<DataSource>)query.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Integer> findDisabledIdByRequestType(final int requestTypeId) {
		List<Integer> dataSourceIDList = new ArrayList<Integer>();		
		
		Query query = createNativeQuery("select ds.id from hib.disableddatasource d left join hib.datasource ds on ds.id=d.datasourceid where d.requesttypeid=:rtid");
		query.setParameter("rtid", requestTypeId);

		List<Object> resultList = query.getResultList();
		if( resultList != null ) {

			for (Object obj : resultList) {
				dataSourceIDList.add( ((Integer)obj) );
			}//end for

		}//end if
		
		return dataSourceIDList;
	}
	
	
	@Override
	@SuppressWarnings("unchecked")
	public List<DataSource> findByHeaderIdAndRequestType(final int dataSourceHeaderId, final int requestTypeId) {
		List<DataSource> dataSourceList = new ArrayList<DataSource>();		

		Query query = createNativeQuery("select ds.id from hib.datasourcedisplay d left join hib.datasource ds on ds.id=d.datasourceid where d.datasourceheaderid=:hid and requesttypeid=:rtid");
		query.setParameter("hid", dataSourceHeaderId);
		query.setParameter("rtid", requestTypeId);

		List<Object> resultList = query.getResultList();
		if( resultList != null ) {

			for (Object obj : resultList) {

				try {

					DataSource ds = findById( ((Integer)obj).intValue() );
					if( ds != null ) {
						dataSourceList.add( ds );
					}//end if

				} catch( Exception exc ) {
					//TODO: log the exception, just in case
				}

			}//end for
		}//end if
		
		return dataSourceList;
	}
	
}
