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

import java.math.BigDecimal;
import java.util.List;

import gov.va.med.esr.common.model.person.id.PersonIdEntityKeyImpl;
import gov.va.med.esr.service.EligibilityEnrollmentService;
import gov.va.med.fw.batchprocess.AbstractDataQueryProcess;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;

/**
 * Batch process to check for the presence of Combat Veteran eligibility and a
 * CV End Date that is in the past. If such a combination is found, the E&E
 * determination should be executed to recalculate the person's eligibilities.
 * 
 * @author Carlos Ruiz
 * @version 1.0
 */
public class CVEndDateProcess extends AbstractDataQueryProcess {

    private EligibilityEnrollmentService eligibilityEnrollmentService = null;    
    
    protected void processData(DataProcessExecutionContext context, List acquiredData) {
        
        if (logger.isInfoEnabled())
            logger.info("CV End Date batch process: Query result Size="+(acquiredData == null ? 0 : acquiredData.size()));
        
        if (acquiredData == null)
            return;
        
        for (int i = 0; i < acquiredData.size(); i++) {
            BigDecimal personId = (BigDecimal) acquiredData.get(i);
            
            if(logger.isDebugEnabled())
                logger.debug("Processing person # " + (i+1) + " with id = " + personId);
            try {
                this.getEligibilityEnrollmentService().processCalculateEE(new PersonIdEntityKeyImpl(personId), true, true);
                context.getProcessStatistics().incrementNumberOfSuccessfulRecords();
            } catch (Exception ex) {
                context.getProcessStatistics().incrementNumberOfErrorRecords();
                String errMsg = "Error while executing CV End Date batch process for person " + personId;
                context.getExceptionData().add(errMsg+ " Reason: "+ ex.getMessage());
                if(logger.isWarnEnabled())
                    logger.warn(errMsg + " Reason: ", ex);
            }
        }
        
        if(logger.isDebugEnabled()) {
            logger.debug("CVEndDateProcess: Processing complete.");
            logger.debug("CVEndDateProcess: Successful records count = "+context.getProcessStatistics().getNumberOfSuccessfulRecords());
            logger.debug("CVEndDateProcess: Failure records count ="+context.getProcessStatistics().getNumberOfErrorRecords());
        }
    }

    /**
     * @return Returns the eligibilityEnrollmentService.
     */
    public EligibilityEnrollmentService getEligibilityEnrollmentService() {
        return eligibilityEnrollmentService;
    }

    /**
     * @param eligibilityEnrollmentService The eligibilityEnrollmentService to set.
     */
    public void setEligibilityEnrollmentService(
            EligibilityEnrollmentService eligibilityEnrollmentService) {
        this.eligibilityEnrollmentService = eligibilityEnrollmentService;
    }
}
