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

import gov.va.med.cds.ars.requestresponse.generated.CensusPostProcessingStatusReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.CensusPostProcessingStatusReportIDType;
import gov.va.med.cds.ars.requestresponse.generated.CensusPostProcessingStatusReportType;
import gov.va.med.cds.ars.requestresponse.generated.HTReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.HTResponseType;
import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.exception.PersistenceException;

import java.util.List;

import javax.xml.datatype.XMLGregorianCalendar;

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

public class CensusPostProcessingStatusReportPersistenceManager extends AbstractReadableReportsPersistenceManager 
	implements CensusPostProcessingStatusReportPersistenceManagerInterface {

	protected String censusPostProcessingStatusReportQuery;
	@Override
	public HTResponseType performReadReportAggregate(HTReportFilterType aReportFilter) throws PersistenceException {
		
		CensusPostProcessingStatusReportFilterType filter = aReportFilter.getCensusPostProcessingStatusReportFilter();
		
		XMLGregorianCalendar xmlStartDate = filter.getStartDate();
		XMLGregorianCalendar xmlEndDate = filter.getEndDate();
		
		java.sql.Date sqlStartDate = formatDate(xmlStartDate);
		java.sql.Date sqlEndDate = formatDate(xmlEndDate);
		
		Session aSession = this.sessionFactory.getCurrentSession();
		
		List<CensusPostProcessingStatusReportType> results = null;
		try {
			Query query = aSession.getNamedQuery( censusPostProcessingStatusReportQuery );
			    query.setDate("startDate", sqlStartDate);
			    query.setDate("endDate", sqlEndDate);
			
			    if ( LOGGER.isDebugEnabled() )
			    {
			        LOGGER.debug("========== Calling CensusWeeklyVendorStatusReport query procedure: " + censusPostProcessingStatusReportQuery + " ======"  );
			        LOGGER.debug( " CensusWeeklyVendorStatusReport startDate: '" + sqlStartDate  + "'");
			        LOGGER.debug( " CensusWeeklyVendorStatusReport   endDate: '" + sqlEndDate + "'");
			    }
			    
			    results =(List<CensusPostProcessingStatusReportType>) queryForReportData( query );
		} finally{ 
			if( aSession != null){
				aSession.close();
			}
		}
		
		if( results.size() != 1){
			throw new PersistenceException(ErrorCodeEnum.CENSUS_REPORT_RECORD_COUNT_INVALID , String.valueOf(results.size()));
		}
		
		CensusPostProcessingStatusReportType data = results.get(0);
		
		data.setReportID(CensusPostProcessingStatusReportIDType.CENSUS_POST_PROCESSING_STATUS_REPORT);
	    responseType.setCensusPostProcessingStatusReportData(data);
		return responseType;
		
	}
	
	public void setCensusPostProcessingStatusReportQuery(
			String censusPostProcessingStatusReportQuery) {
		this.censusPostProcessingStatusReportQuery = censusPostProcessingStatusReportQuery;
	}
	

}
