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


package gov.va.med.fw.batchprocess;

import java.util.List;

import gov.va.med.fw.io.parser.FileParserListener;

/**
 * Specialization of AbstractDataFileProcess that allows for record processing
 * in variable amounts at a time, rather than the entire List of data at once.  The
 * implementation of acceptData determines when the List of data should be
 * processed.
 *
 * Created Mar 7, 2006 1:37:28 PM
 * @author DNS   BOHMEG
 */
public abstract class AbstractDataFileListenerProcess extends AbstractDataFileProcess
		implements FileParserListener {

	//provide a consistent keyword for exception data in the context
	public static final String ERROR_KEYWORD ="Error processing data: ";

	protected DataProcessExecutionContext createDataProcessExecutionContext() {
		DataFileProcessExecutionContext context = (DataFileProcessExecutionContext) super.createDataProcessExecutionContext();
		context.setFileParserListener(this);
		return context;
	}

	/** from FileParserListener interface so must be public */
	public abstract boolean acceptData(DataFileProcessExecutionContext context, String nextRowRawData, List beans);

	public boolean isInterrupted(DataFileProcessExecutionContext context) {
		return super.isInterrupted(context);
	}

	protected final void processData(DataProcessExecutionContext context, List acquiredData) {
		if(acquiredData == null || acquiredData.isEmpty())
			return;

		processData((DataFileProcessExecutionContext) context, acquiredData);
	}

	/** from FileParserListener interface so must be public */
	public final void processData(DataFileProcessExecutionContext context, List acquiredData) {
		processDataRecords(context, acquiredData);

		if(shouldUpdateJobResult(context))
			this.updateJobResult(context);
	}

	public abstract void processDataRecords(DataFileProcessExecutionContext context, List acquiredData);

	/** from FileParserListener interface so must be public - not marked final so can be overridden */
	public boolean beanCreationFailure(DataFileProcessExecutionContext context, String nextRowRawData,
			Exception e) {
		context.getProcessStatistics().incrementNumberOfErrorRecords();
		context.getExceptionData().add(ERROR_KEYWORD + context.getCurrentRowRawData() + ".\n" + e.getMessage() + ".\n" + e.getStackTrace().toString());
		return true;
	}

	/** from FileParserListener interface so must be public - not marked final so can be overridden */
	public void beanCreationSuccess(DataFileProcessExecutionContext context, String nextRowRawData) {
		// default is no-op since creation does not always indicate complete success
	}

	protected boolean shouldUpdateJobResult(DataFileProcessExecutionContext context) {
		return context.getProcessStatistics().isTotalNumberMod(DEFAULT_JOB_RESULT_UPDATE_INTERVAL);
	}
}
