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

import gov.va.med.fw.batchprocess.AbstractLegacyDataProcess;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.batchprocess.AacExportProcessStatistics;
import gov.va.med.fw.batchprocess.ProcessStatistics;
import gov.va.med.fw.service.ServiceException;

public class InitiateCMSLetterExportProcess extends AbstractLegacyDataProcess {

	protected void executeProcess(DataProcessExecutionContext context)
			throws Exception {
		try {
			CmsExportCommand cmd = (CmsExportCommand) getComponent("cmsExportCommand");
			String[] args = null;

			if (context.getExecutionArguments() != null) {
				if (context.getExecutionArguments() instanceof String[]) {
					args = (String[]) context.getExecutionArguments();
				} else {
					// must be a single argument as String
					args = new String[] { (String) context
							.getExecutionArguments() };
				}
			}
			CommsExportStatistics legacyStats = cmd.execute(args, context, this);
			if (legacyStats != null) {
				AacExportProcessStatistics aacstats = prepareStatistics(
						context, legacyStats);
			}
		} catch (Exception e) {
			logger.error("Exception executing CmsExportCommand", e);
			throw new ServiceException(e);
		}

	}

	public void updateLiveJobStatistics(DataProcessExecutionContext context,
			CommsExportStatistics stats) {
		AacExportProcessStatistics aacstats = prepareStatistics(context, stats);
		if (logger.isTraceEnabled()) {
			logger.debug("updateLiveJobStatistics:"
					+ context.getProcessStatistics().getNumberOfTotalRecords());
		}

		if (context.getProcessStatistics().isTotalNumberMod(
				DEFAULT_JOB_RESULT_UPDATE_INTERVAL)) {
			if (logger.isTraceEnabled()) {
				logger.trace("updateLiveJobStatistics:Updating the job stats");
			}

			this.updateJobResult(context);
		}
	}

	private AacExportProcessStatistics prepareStatistics(
			DataProcessExecutionContext context, CommsExportStatistics stats) {
		AacExportProcessStatistics aacstats = (AacExportProcessStatistics) context
				.getProcessStatistics();

		aacstats.setNumberOfTotalRecords(stats.getNumberSent()
				+ stats.getNumberCancelled() + stats.getNumberRejected());
		aacstats.setNumberOfSuccessfulRecords(stats.getNumberSent());
		aacstats.setNumberOfErrorRecords(stats.getNumberRejected()
				+ stats.getNumberCancelled());

		aacstats.setNumberWithException(stats.getNumberWithException());
		return aacstats;
	}

	protected ProcessStatistics createProcessStatistics() {
		return new AacExportProcessStatistics();
	}
}
