package gov.va.med.esr.common.batchprocess;

import java.util.List;

import gov.va.med.esr.service.IRSTransmissionService;
import gov.va.med.esr.service.SystemParameterService;
import gov.va.med.fw.batchprocess.AbstractDataQueryIncrementalProcess;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.batchprocess.DataQueryProcessExecutionContext;
import gov.va.med.fw.service.ServiceException;

/**
 * Batch process to request acknowledgments for unprocessed IRS batch submissions for ACA
 *
 * WI# 218485
 * Create 13 Sep 2015
 * @author DNS   faulkj
 *
 * @version 1.0
 */
public class RequestIRSAcknowledgmentsProcess extends AbstractDataQueryIncrementalProcess {

	private static final int DEFAULT_JOB_RESULT_UPDATE_INTERVAL = 100;

	private SystemParameterService systemParameterService = null;

	private static final String IRS_ACK_PERIOD = "IRS Ack Period";

	private String ackPeriod;
	private IRSTransmissionService irsTransmissionService = null;

	protected void executeProcess(DataProcessExecutionContext context) throws Exception {

		ackPeriod = this.getSystemParameterService().getByName(IRS_ACK_PERIOD).getValue();
		int hours = Integer.valueOf(ackPeriod);

		this.setParamNames(new String[] {"ackHours"});
		this.setParamValues(new Integer[] {hours});

		super.executeProcess(context);
	}

	protected void processData(DataQueryProcessExecutionContext context,
			List acquiredData) {

		if (acquiredData == null){
			return;
		}

		for (int i = 0; i < acquiredData.size() && !isInterrupted(context); i++) {
			if (acquiredData.get(i) != null && !acquiredData.get(i).toString().isEmpty()) {
				String receiptId = acquiredData.get(i).toString();
				if (receiptId != null && receiptId.length() > 0) {
					try {
						this.getIrsTransmissionService().requestAcknowledgment(receiptId);
						context.getProcessStatistics().incrementNumberOfSuccessfulRecords();
					} catch (ServiceException e) {
						logger.error("Error in IRS acknowledgmeent process:" + e);
						context.getProcessStatistics().incrementNumberOfErrorRecords();
					}

					//processEntityData(context, receiptId);
				}
			}
		}
	}

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

	public SystemParameterService getSystemParameterService() {
		return systemParameterService;
	}

	public void setSystemParameterService(
			SystemParameterService systemParameterService) {
		this.systemParameterService = systemParameterService;
	}

	public IRSTransmissionService getIrsTransmissionService() {
		return irsTransmissionService;
	}

	public void setIrsTransmissionService(IRSTransmissionService irsTransmissionService) {
		this.irsTransmissionService = irsTransmissionService;
	}

}
