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.VPIDEntityKey;
import gov.va.med.esr.service.trigger.PersonTrigger;
import gov.va.med.esr.service.trigger.PersonTriggerEvent;
import gov.va.med.fw.batchprocess.AbstractDataFileIncrementalProcess;
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.util.List;



public class SendingZ11MessagesProcess extends AbstractDataFileIncrementalProcess {
	private TriggerRouter triggerRouter;

	public void processDataRecords(
			DataFileProcessExecutionContext context, List beans) {
		
		if (logger.isDebugEnabled())
		{
			int listSize = 0;
			if ( beans != null ) listSize = beans.size();
			
			logger.error("Processing VPID  " + listSize);
		}
		
		for ( int i=0; beans != null && i< beans.size(); i++)
		{
			VPIDFileData dataRecord = (VPIDFileData) beans.get(i);

			try {
				VPIDEntityKey vpidEntityKey = CommonEntityKeyFactory
	            	.createVPIDEntityKey(dataRecord.getVpid());

				if (logger.isDebugEnabled())
			           logger.error("Processing VPID  " + dataRecord.getVpid());
				
				getTriggerRouter().processTriggerEvent(getTriggerEvent(vpidEntityKey));
				context.getProcessStatistics().incrementNumberOfSuccessfulRecords();
				
			} catch (Exception e) {
				if (logger.isErrorEnabled())
		           logger.error("Error adding PSIM Correlation for VPID " + dataRecord.getVpid(), e);
		            
				context.getProcessStatistics().incrementNumberOfErrorRecords();
			}
			finally
			{
				// Check if we need to update the job result
				if(shouldUpdateJobResult(context))
						updateJobResult(context);
				
				if ( isInterrupted(context))
				{
					break;
				}
			}
			
		}
	}


	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;
	}
}
