package gov.va.med.cds.ars.persistence;

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

import org.hibernate.Query;
import org.hibernate.Session;

import gov.va.med.cds.ars.requestresponse.generated.FYQtrReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.HTHFYQtrReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.HTHFYQtrReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.HTReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.HTResponseType;
import gov.va.med.cds.exception.PersistenceException;

public class HthFiscalYearQuarterReportPersistenceManager extends AbstractReadableReportsPersistenceManager
		implements ReadableReportsPersistenceManagerInterface {
	private String hthQtrYearDataQuery = "CensusReports.hthFYQtrReport";

	@Override
	public HTResponseType performReadReportAggregate(HTReportFilterType aReportFilter) throws PersistenceException {
		HTHFYQtrReportFilterType filter = aReportFilter.getHthFYQtrReportFilter();
		HTHFYQtrReportDataType data = new HTHFYQtrReportDataType();
		Session session = this.sessionFactory.getCurrentSession();

		List<FYQtrReportDataType> results = null;

		try {
			results = getHthFYQuarterData(session, filter);

			data.getReportData().addAll(results);
			data.setReportID(filter.getReportID());
		} finally {
			session.close();
		}

		responseType.setHthFYQtrReportData(data);

		return responseType;
	}

	@SuppressWarnings("unchecked")
	private List<FYQtrReportDataType> getHthFYQuarterData(Session aSession, HTHFYQtrReportFilterType hthReportFilter)
			throws PersistenceException {
		Query query = aSession.getNamedQuery(hthQtrYearDataQuery);

		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("+++++ Calling stored proc: *****(  " + hthQtrYearDataQuery + "  )*****");
		}

		List<FYQtrReportDataType> results = new ArrayList<FYQtrReportDataType>();

		try {
			results = (List<FYQtrReportDataType>) queryForReportData(query);
		} catch (Exception e) {
			LOGGER.error("Exception in getHthFYQuarterData " + e);
		}

		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("----- Done with stored proc " + hthQtrYearDataQuery);
		}

		return results;
	}

	public void setHthQtrYearDataQuery(String hthQtrYearDataQuery) {
		this.hthQtrYearDataQuery = hthQtrYearDataQuery;
	}
}
