

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


import gov.va.med.cds.ars.filter.StatusInterface;
import gov.va.med.cds.ars.requestresponse.generated.HTBaseReportType;
import gov.va.med.cds.ars.requestresponse.generated.HTReportFilterType;
import gov.va.med.cds.ars.requestresponse.generated.HTReportSurveyType;
import gov.va.med.cds.ars.requestresponse.generated.HTResponseType;
import gov.va.med.cds.ars.requestresponse.generated.NationalDistributionLocationReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.NationalDistributionReportDataType;
import gov.va.med.cds.ars.requestresponse.generated.NationalDistributionReportFilterType;
import gov.va.med.cds.exception.PersistenceException;

import java.util.List;

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


/**
    5. Report: National Distribution of All Surveys by Vendor
        Available Parameters:
            1. N/A
        Aggregate Returned:
            1. Count total number of VR-12 surveys
            2. Count total number of Patient Satisfaction surveys
            3. Count total number of both surveys (VR-12 and Patient Satisfaction)
            4. Count total number of surveys by vendor
            5. Return the date of last survey submission for each vendor
        Survey Status:
            1. Considers surveys with an ACCEPTED status for #1, #2, and #3
            2. Considers surveys with all statuses for #4 and #5 * @author DNS   BRUSHS
 *
 */
public class NationalDistributionReportsPersistenceManager
    extends
        AbstractReadableReportsPersistenceManager
    implements
        ReadableReportsPersistenceManagerInterface
{
    protected String nationalDistributionQuery = "SurveyReports.nationalDistribution";
    protected String acceptedSurveyCountQuery = "SurveyReports.countSurveysNationalDist";

    
    @Override
    public HTResponseType performReadReportAggregate( HTReportFilterType aReportFilter )
        throws PersistenceException
    {
    	NationalDistributionReportFilterType filter = aReportFilter.getNationalDistributionReportFilter();
        NationalDistributionReportDataType data = new NationalDistributionReportDataType();
        Session session = this.sessionFactory.getCurrentSession();
        
        //defect 410810: retain the survey type of incoming request
        HTReportSurveyType requestSurveyType = filter.getSurveyType();
        String surveyVersion = filter.getSurveyVersion();
        
        try
        {
            List<NationalDistributionLocationReportDataType> results = null;
            Integer surveyCount = null;
            Integer totalCount = null;

            filter = aReportFilter.getNationalDistributionReportFilter();
            
            // set up filter to ignore what's passed in
            filter.setSurveyVersion( "All Versions" );

            // get national report by vendor (4, 5)
            filter.setSurveyType( HTReportSurveyType.ALL_SURVEYS );
            results = nationalDistributionReport( session, filter );
            data.getReportData().addAll( results );
            
            // get national count for all survey types (1-3)

            // vr12 (1)
            filter.setSurveyType( HTReportSurveyType.VR_12_ADL );
            surveyCount = getAcceptedSurveyCount( session, filter );
            data.setNumberOfVR12Records( surveyCount );
            totalCount = surveyCount;

            // ps (2)
            filter.setSurveyType( HTReportSurveyType.PATIENT_SATISFACTION );
            surveyCount = getAcceptedSurveyCount( session, filter );
            data.setNumberOfPatientSatisfactionRecords( surveyCount );
            totalCount += surveyCount;

            // total (3)
            data.setNumberOfRecordsConsidered( totalCount );
            data.setReportID( filter.getReportID() );            

            // defect 410810: retain the survey type of incoming request
            filter.setSurveyType(requestSurveyType);
            filter.setSurveyVersion( surveyVersion );
            
            if ( LOGGER.isDebugEnabled() )
            {
                LOGGER.debug( " result of national distribution report: " + data );
            }
        }
        finally
        {
            session.close();
        }
        
        responseType.setNationalDistributionReportData( data );
        
        return responseType;
    }
    

    @SuppressWarnings( "unchecked" )
    private List<NationalDistributionLocationReportDataType> nationalDistributionReport( Session aSession, NationalDistributionReportFilterType aNationalDistributionReportFilter )
        throws PersistenceException
    {
        String surveyVersion = aNationalDistributionReportFilter.getSurveyVersion();
        String surveyType = aNationalDistributionReportFilter.getSurveyType().value();
        
        Query query = aSession.getNamedQuery( nationalDistributionQuery );
        query.setString( "surveyVersion", surveyVersion );
        query.setString( "surveyType", surveyType );
        
        if ( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug( "+++++ Calling National Distribution stored proc: *****(  " + nationalDistributionQuery + "  )*****" );
            LOGGER.debug( " surveyVersion: " + surveyVersion );
            LOGGER.debug( " surveyType: " + surveyType );
        }
        
        List<NationalDistributionLocationReportDataType> results = ( List<NationalDistributionLocationReportDataType> )queryForReportData( query );
        
        if ( LOGGER.isDebugEnabled() )
        {
            System.out.println( "----- Done with National Distribution stored proc" );
        }

        return results;
    }


    @SuppressWarnings( "unchecked" )
    protected Integer getAcceptedSurveyCount( Session aSession, NationalDistributionReportFilterType aReportFilter )
    {
        String surveyVersion = aReportFilter.getSurveyVersion();
        String surveyType = aReportFilter.getSurveyType() == null ? null : aReportFilter.getSurveyType().value();

        Query query = aSession.getNamedQuery( acceptedSurveyCountQuery );
        query.setString( "surveyVersion", surveyVersion );
        query.setString( "surveyType", surveyType );
        query.setString( "acceptedStatus", StatusInterface.STATUS_ACCEPTED );

        if ( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug( "+++++ Calling Count Surveys stored proc: *****(  " + acceptedSurveyCountQuery + "  )*****" );
            LOGGER.debug( " surveyVersion: " + surveyVersion );
            LOGGER.debug( " surveyType: " + surveyType );
            LOGGER.debug( " acceptedStatus: " + StatusInterface.STATUS_ACCEPTED );
        }

        List<HTBaseReportType> results = null;
        Integer count = null;
        try
        {
            results = query.list();
            
            if ( LOGGER.isDebugEnabled() )
            {
                LOGGER.debug( "Count result size: " + results.size() );
//                for ( Object object : results )
//                {
//                    LOGGER.debug( object.getClass().getName() + " *** " + object );
//                }
            }
            
            if ( ( results != null ) && ( results.size() > 0 ) && ( results.get( 0 ) instanceof HTBaseReportType ) )
            {
                count = ( ( HTBaseReportType )results.get( 0 ) ).getNumberOfRecordsConsidered();
            }
        }
        catch ( HibernateException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw e;
        }
        
        if ( LOGGER.isDebugEnabled() )
        {
            LOGGER.debug( "----- Done with Count Surveys stored proc" );
        }
        
        return count;
    }


    public void setNationalDistributionQuery( String aNationalDistributionQuery )
    {
        this.nationalDistributionQuery = aNationalDistributionQuery;
    }


    public void setAcceptedSurveyCountQuery( String aAcceptedSurveyCountQuery )
    {
        this.acceptedSurveyCountQuery = aAcceptedSurveyCountQuery;
    }

}

