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

import gov.va.med.cds.ars.exception.ValidationException;
import gov.va.med.cds.ars.requestresponse.generated.CensusVendorStatusDataType;
import gov.va.med.cds.ars.requestresponse.generated.CensusWeeklyVendorStatusReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.CensusWeeklyVendorStatusReportFilterType;
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;

import java.util.List;

import javax.xml.datatype.XMLGregorianCalendar;

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

public class CensusWeeklyVendorStatusReportPersistenceManager extends AbstractReadableReportsPersistenceManager 
	implements CensusWeeklyVendorStatusReportPersistenceManagerInterface {
	
	protected String censusWeeklyVendorStatusReportQuery;
		
	@Override
	public HTResponseType performReadReportAggregate(
			HTReportFilterType aReportFilter) throws PersistenceException, ValidationException {
		
		CensusWeeklyVendorStatusReportFilterType filter = aReportFilter.getCensusWeeklyVendorReportStatusFilter();

		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<CensusVendorStatusDataType> results = null;
		try {
			Query query = aSession.getNamedQuery( censusWeeklyVendorStatusReportQuery );
			    query.setDate("startDate", sqlStartDate);
			    query.setDate("endDate", sqlEndDate);
			
			    if ( LOGGER.isDebugEnabled() )
			    {
			        LOGGER.debug("========== Calling CensusWeeklyVendorStatusReport query procedure: " + censusWeeklyVendorStatusReportQuery + " ======"  );
			        LOGGER.debug( " CensusWeeklyVendorStatusReport startDate: '" + sqlStartDate  + "'");
			        LOGGER.debug( " CensusWeeklyVendorStatusReport   endDate: '" + sqlEndDate + "'");
			    }
			    
			    results = (List<CensusVendorStatusDataType>)queryForReportData(query);
			    
		} finally{ 
			if( aSession != null){
				aSession.close();
			}
		}
		
		CensusWeeklyVendorStatusReportDataType data = new CensusWeeklyVendorStatusReportDataType();
		CensusWeeklyVendorStatusReportDataType.Vendors vendors = new CensusWeeklyVendorStatusReportDataType.Vendors();
		vendors.getVendor().addAll(results);
		data.setVendors(vendors);
		data.setReportID(filter.getReportID());
	    responseType.setCensusWeeklyVendorStatusReportData(data);
		
		return responseType;
		
	}

	public void setCensusWeeklyVendorStatusReportQuery(
			String censusWeeklyVendorStatusReport) {
		this.censusWeeklyVendorStatusReportQuery = censusWeeklyVendorStatusReport;
	}

}
