/********************************************************************
 * Copyright © 2006 VHA. All rights reserved
 ********************************************************************/


package gov.va.med.fw.batchprocess;

import gov.va.med.fw.util.InvalidConfigurationException;

import java.util.Iterator;
import java.util.List;

/**
 * Abstract base class for incremental processing for multiple queries.
 * Incremental queries are supported, but not required. 
 * 
 * Created Apr 24, 2006 10:33:36 PM
 * @author DNS   BOHMEG
 */

public abstract class AbstractDataQueriesProcess extends
		AbstractDataQueryIncrementalProcess {
	private List dataQueries;
	
	protected final void executeProcess(DataProcessExecutionContext context) throws Exception {
		List acquiredData = null;
		
		DataQueryProcessExecutionContext queryContext = (DataQueryProcessExecutionContext) context;
		Iterator itr = dataQueries.iterator();
		DataQueryDetail query = null;
		while(itr.hasNext()) {
			query = (DataQueryDetail) itr.next();
			queryContext.setCurrentDataQuery(query);
			queryContext.setCurrentRecord(0);
            prepareDataQueryDetail(queryContext, query);
            
			while(! isInterrupted(context)) {
				if(query.isIncremental()) {
					acquiredData = acquireData(queryContext);
					if(acquiredData == null || acquiredData.isEmpty())
						break;
					processQueryData(queryContext, query, acquiredData);
				} else {
					acquiredData = executeQuery(queryContext);
					processQueryData(queryContext, query, acquiredData);
					break;
				}
			}
			
		}
		
		if(!isHandleEachFetchSeparately())
			handleDataProcessCompleted(context);
	}
	
    // subclass can override this empty implementation
    protected void prepareDataQueryDetail(DataQueryProcessExecutionContext context, DataQueryDetail query) {
        // do nothing
    }
	
	private void processQueryData(DataQueryProcessExecutionContext context, DataQueryDetail query, List acquiredData) throws Exception {
		if(query.getProcessor() != null)
			query.getProcessor().processAcquiredData(context, acquiredData);
		else
			processData(context, acquiredData);
		
		if(isHandleEachFetchSeparately())
			handleDataProcessCompleted(context);																
	}

	protected void validateQuery() {
		if(dataQueries == null || dataQueries.isEmpty())
			throw new InvalidConfigurationException("dataQueries must contain at least one query");
	}


    
    /**
     * @return Returns the dataQueries.
     */
    public List getDataQueries() {
        return dataQueries;
    }


    
    /**
     * @param dataQueries The dataQueries to set.
     */
    public void setDataQueries(List dataQueries) {
        this.dataQueries = dataQueries;
    }
}
