/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.report.data.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

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

import gov.va.med.fw.report.ReportConfiguration;
import gov.va.med.fw.report.data.QueryCriteria;
import gov.va.med.fw.report.data.ReportDataException;

import gov.va.med.esr.common.model.lookup.AACIndicator;
import gov.va.med.esr.common.model.report.ReportParameterSet;
import gov.va.med.esr.common.model.report.ReportSetup;
import gov.va.med.esr.common.model.report.ReportVBAQueryStatus;
import gov.va.med.esr.common.report.data.CommonCriteria;
import gov.va.med.esr.common.report.data.StandardReportCriteria;

/**
 * @author DNS   KATIKM
 *
 */
public class VBAStatusQueryDAOImpl extends AbstractStandardReportDataDAOImpl {
	
    private static final long serialVersionUID = -2129466633314231407L;

    protected Query buildQuery(ReportConfiguration config, Session session) throws ReportDataException {

		//Get the query with default from and to date parameters
		Query query = null;
		if (getNameResolver() != null) {
			query = this.getNamedQuery(getNameResolver().getReportName(config),session);
		}
		else {
			query = this.getNamedQuery(session);
		}
	
		//Set in the base class	
		QueryCriteria reportCriteria = config.getQueryCriteria();
		StandardReportCriteria criteria = (StandardReportCriteria)reportCriteria;
		ReportSetup setup = criteria.getReportSetup();
	
		ReportParameterSet parameters = setup != null ? setup.getParameterSet() : null;
		if( parameters == null ) {
			throw new ReportDataException("Missing report parameters in report " + config.getReportID() );
		}
		query.setDate(CommonCriteria.START_DATE, parameters.getFromDate());
		query.setDate(CommonCriteria.END_DATE, parameters.getToDate());
		
		//set VBA statuses
		Set vbaQueryStatuses = parameters.getVBAQueryStatuses();
		query.setParameterList("vbaQueryStatusList", getVBAQueryStatusIds(vbaQueryStatuses));
		return query;
	}
	
	private List getVBAQueryStatusIds(Set vbaQueryStatuses){
	    Iterator i = vbaQueryStatuses != null ? vbaQueryStatuses.iterator() : null;
	    ArrayList list = new ArrayList();
	    while( i != null && i.hasNext() ) {
	        ReportVBAQueryStatus qryStatus = (ReportVBAQueryStatus)i.next();
	        if(qryStatus != null) 
	        	list.add(((AACIndicator)qryStatus.getLookup()).getIdentifier());
	    }
	    return list;
	}
}
