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

import gov.va.med.esr.common.model.CommonEntityKeyFactory;
import gov.va.med.esr.common.model.person.id.PersonEntityKey;
import gov.va.med.esr.common.model.person.id.PersonIdEntityKey;
import gov.va.med.esr.service.trigger.PersonTrigger;
import gov.va.med.esr.service.trigger.PersonTriggerEvent;
import gov.va.med.fw.batchprocess.AbstractDataFileSingleRowIncrementProcess;
import gov.va.med.fw.batchprocess.DataFileProcessExecutionContext;
import gov.va.med.fw.service.trigger.TriggerEvent;
import gov.va.med.fw.service.trigger.TriggerRouter;

import java.io.PrintWriter;
import java.io.StringWriter;

public class PCMMZ11Process extends AbstractDataFileSingleRowIncrementProcess {
	private TriggerRouter triggerRouter;

	protected boolean processDataRecord(
			DataFileProcessExecutionContext context, Object bean) {
		
		boolean success = false;

		try {
			PersonIdFileData dataRecord = (PersonIdFileData) bean;
	        PersonIdEntityKey key = CommonEntityKeyFactory.createPersonIdEntityKey(dataRecord.getPersonId());
    		getTriggerRouter().processTriggerEvent(getTriggerEvent(key));

    		success = true;
		} catch (Exception e) {
			handleFailure(context, (PersonIdFileData) bean, e);
		}
	            
       if(logger.isDebugEnabled()) {
            logger.debug(getProcessName() + ": Processing of current batch complete.");
            logger.debug(getProcessName() + ": Successful records count = "+context.getProcessStatistics().getNumberOfSuccessfulRecords());
            logger.debug(getProcessName() + ": 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,
			PersonIdFileData data, Exception e) {
		
		String exceptionText = null;
		if (e == null) {
			exceptionText = "Error: Unable to process personId data: " + data;
		}
		else {
				exceptionText = "Error: Unable process personId data: "
						+ data + " because of exception: " + e;		
		}
		if (logger.isErrorEnabled()) {
			logger.error(exceptionText);
		}
		context.getExceptionData().add(data);
		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);
	    }
	}

	private TriggerEvent getTriggerEvent(PersonEntityKey key)
	{
		PersonTriggerEvent triggerEvent = new PersonTriggerEvent(PersonTrigger.DestinationType.MESSAGING,
                PersonTrigger.TargetType.VISTA, PersonTrigger.DispatchType.NOTIFY,  PersonTrigger.DataType.ELIGIBILITY);
		triggerEvent.setPersonId(key);
		return triggerEvent;
	}


	public TriggerRouter getTriggerRouter() {
		return triggerRouter;
	}


	public void setTriggerRouter(TriggerRouter triggerRouter) {
		this.triggerRouter = triggerRouter;
	}
}

