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

import gov.va.med.esr.service.LookupService;
import gov.va.med.esr.service.PreferredFacilityService;
import gov.va.med.fw.batchprocess.AbstractDataFileSingleRowIncrementProcess;
import gov.va.med.fw.batchprocess.DataFileProcessExecutionContext;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Nightly update process for preferred facility Primary Care Physician data update from PCMM
 */
public class PCMMUpdateProcess extends
		AbstractDataFileSingleRowIncrementProcess {
	
    private LookupService lookupService = null;
 	private PreferredFacilityService preferredFacilityService;
    
 	/* (non-Javadoc)
	 * @see gov.va.med.fw.batchprocess.AbstractDataFileSingleRowIncrementProcess#processDataRecord(gov.va.med.fw.batchprocess.DataFileProcessExecutionContext, java.lang.Object)
	 */
	protected boolean processDataRecord(
			DataFileProcessExecutionContext context, Object bean) {

		boolean success = false;

		try {
			preferredFacilityService.processPCMMData((PCMMImportData) bean);
			success = true;
		} catch (Exception e) {
			handleFailure(context, (PCMMImportData) bean, e);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("PCMMUpdateProcess: Processing complete.");
			logger.debug("PCMMUpdateProcess: Successful records count = "
					+ context.getProcessStatistics().getNumberOfSuccessfulRecords());
			logger.debug("PCMMUpdateProcess: Failure records count ="
					+ context.getProcessStatistics().getNumberOfErrorRecords());
		}

		// Update statistics more frequently than once per batch (default size 500)
		if (context.getProcessStatistics().isTotalNumberMod(
				DEFAULT_JOB_RESULT_UPDATE_INTERVAL))
			this.updateJobResult(context);

		return success;
	}

	private void handleFailure(DataFileProcessExecutionContext context,
			PCMMImportData pcmmData, Exception e) {
		String exceptionText = null;
		if (e == null) {
			exceptionText = "Error: Unable to process PCMM data: " + pcmmData;
		}
		else {
				exceptionText = "Error: Unable process PCMM data: "
						+ pcmmData + " because of exception: " + e;		
		}
		if (logger.isErrorEnabled()) {
			logger.error(exceptionText);
		}
		context.getExceptionData().add(pcmmData);
		context.getExceptionData().add(exceptionText + "\n\n");
		
        if ( e != null )
        {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            String trackTrace =  sw.toString();
            context.getExceptionData().add(trackTrace);
        }
	}

	/**
	 * @return Returns the lookupService.
	 */
	public LookupService getLookupService() {
		return this.lookupService;
	}

	/**
	 * @param lookupService The lookupService to set.
	 */
	public void setLookupService(LookupService lookupService) {
		this.lookupService = lookupService;
	}

	public PreferredFacilityService getPreferredFacilityService() {
		return preferredFacilityService;
	}

	public void setPreferredFacilityService(
			PreferredFacilityService preferredFacilityService) {
		this.preferredFacilityService = preferredFacilityService;
	} 
 }
