

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


import gov.va.med.cds.ars.requestresponse.generated.VISNFacilityReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.VISNFacilityDataType;
import gov.va.med.cds.ars.requestresponse.generated.VISNFacilityReportFilterType;
import gov.va.med.cds.exception.PersistenceException;
import gov.va.med.cds.ars.requestresponse.generated.HTReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.HTResponseType;
import gov.va.med.cds.ars.requestresponse.generated.ObjectFactory;

import java.util.List;

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


public class VISNFacilityReportPersistenceManager extends AbstractReadableReportsPersistenceManager 
	implements VISNFacilityReportPersistenceManagerInterface {
    protected String vISNFacilityQuery = "SurveyReports.VISNFacility";
    
    @Override
    public HTResponseType performReadReportAggregate( HTReportFilterType aReportFilter )
        throws PersistenceException
    {
	   
        ObjectFactory objectFactory = new ObjectFactory();
        VISNFacilityReportDataType data = objectFactory.createVISNFacilityReportDataType();
        
        VISNFacilityReportDataType.VisnFacilities visnFacilities = objectFactory.createVISNFacilityReportDataTypeVisnFacilities();
        data.setVisnFacilities( visnFacilities );
        VISNFacilityReportFilterType filter = aReportFilter.getVisnFacilityReportFilter();
        Session session = this.sessionFactory.getCurrentSession();     
        
        try
        {
            List<VISNFacilityDataType> results = null;            
            results = visnFacilityReport( session, filter );

            data.getVisnFacilities().getVisnFacility().addAll( results );
            data.setReportID( filter.getReportID() );
        }
        finally
        {
            session.close();
        }
        
        responseType.setVisnFacilityReportData( data );
        
        return responseType;
        
    }
    

    @SuppressWarnings( "unchecked" )
    private List<VISNFacilityDataType> visnFacilityReport( Session aSession, VISNFacilityReportFilterType aVISNFacilityReportFilter )
        throws PersistenceException
    {        
        Query query = aSession.getNamedQuery( vISNFacilityQuery );
        
        if ( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug("+++++ Calling VISN Facility stored proc: *****(  " + vISNFacilityQuery + "  )*****" );
        }
        
        List<VISNFacilityDataType> results = ( List<VISNFacilityDataType> )queryForReportData( query );
        
        if ( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug( "----- Done with VISN Facility Report stored proc" );
        }

        return results;
    }


    public void setVISNFacilityQuery( String aVISNFacilityQuery  )
    {
        this.vISNFacilityQuery =  aVISNFacilityQuery;
    }
}

