/********************************************************************
 * Copyright © 2004 EDS. All rights reserved
 ********************************************************************/
//Package
package gov.va.med.esr.messaging.batchprocess;

//Java Classes
import gov.va.med.esr.messaging.service.retransmission.MessageLogFinder;
import gov.va.med.esr.messaging.service.retransmission.MessageResender;
import gov.va.med.esr.messaging.service.retransmission.Retransmission;
import gov.va.med.esr.service.MessagingService;
import gov.va.med.esr.service.trigger.RetransmitTriggerEvent;
import gov.va.med.fw.batchprocess.AbstractLegacyDataProcess;
import gov.va.med.fw.batchprocess.DataProcessExecutionContext;
import gov.va.med.fw.service.ServiceException;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.Validate;

/**
 * Class that retransmits outbound messages.
 * 
 * @author Alex Yoon
 * @version 1.0
 */
public class RetransmissionProcess extends AbstractLegacyDataProcess implements Retransmission {
    
    private MessagingService messagingService;
    
    private MessageLogFinder messageLogFinder;
    
    private MessageResender publisher;
    
    private boolean turnedOn = false;
    
    /**
     * Default constructor.
     */
    public RetransmissionProcess() {
        super();
    }
    
    
    /**
     * @return Returns the messagingService.
     */
    public MessagingService getMessagingService()
    {
        return messagingService;
    }
    /**
     * @param messagingService The messagingService to set.
     */
    public void setMessagingService(MessagingService messagingService)
    {
        this.messagingService = messagingService;
    }
    public MessageLogFinder getMessageLogFinder()
    {
        return this.messageLogFinder;
    }

    public void setMessageLogFinder(MessageLogFinder messageLogFinder)
    {
        this.messageLogFinder = messageLogFinder;
    }
    
    public MessageResender getPublisher()
    {
        return this.publisher;
    }

    public void setPublisher(MessageResender publisher)
    {
        this.publisher = publisher;
    }
    
    public boolean getTurnedOn()
    {
        return this.turnedOn;
    }

    public void setTurnedOn(boolean turnedOn)
    {
        this.turnedOn = turnedOn;
    }
     
    /**
     * Method to retransmit outbound messages. This is called from the batch job 
     * 
     * @throws ServiceException
     */
    public int retransmit() throws ServiceException {
        if (logger.isDebugEnabled()) {
            logger.debug("retransmit() was called. ");
        }
        int numberPublished = 0;
        
        //If retransmission is Turned OFF, do nothing.
        if (!this.turnedOn) {
            if (logger.isInfoEnabled()) {
                logger.info("Retransmission is Turned OFF. ");
            }
            return numberPublished;
        }
        
        try {
            //Find list of messages to be retransmitted.
            List messageLogEntries = this.messageLogFinder.find();
            
            retransmit(messageLogEntries);
            numberPublished = messageLogEntries.size();
        }
        catch (ServiceException e) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to find messages to retransmit due to an exception ", e);
            }
        }
        return numberPublished;
    }

    /* (non-Javadoc)
     * @see gov.va.med.esr.messaging.service.retransmission.Retransmission#retransmit(gov.va.med.esr.service.trigger.RetransmitTriggerEvent)
     */
    public void retransmit(RetransmitTriggerEvent retransmitTriggerEvent) throws ServiceException
    {
        if (logger.isDebugEnabled()) {
            logger.debug("Retransmit was called for RetransmitTriggerEvent. ");
        }
        
        try {
            //Resend message.
            this.publisher.resend(retransmitTriggerEvent);
        }
        catch (ServiceException e) {
            if (logger.isErrorEnabled()) {
                logger.error("Failed to resend a message due to an exception ", e);
            }
        }
    }
    
    /**
     * Retransmits a collection of messages
     * 
     * @param messageLogEntries
     * @throws ServiceException
     */
    public void retransmit(List messageLogEntries) throws ServiceException {
        if (logger.isDebugEnabled()) {
            logger.debug("Retransmitted messages of count: " 
                    + (messageLogEntries == null ? 0 :messageLogEntries.size()));
        }
        
        if(messageLogEntries != null)
        {
          String controlId = null;
          for (Iterator iter = messageLogEntries.iterator(); iter.hasNext();)
            {
                controlId = (String) iter.next();
                
                if (controlId != null) {
                    try {
                        //Resend message.
                        this.publisher.resend(controlId);
                    }
                    catch (ServiceException e) {
                        if (logger.isErrorEnabled()) {
                            logger.error("Failed to resend a message due to an exception ", e);
                        }
                    }
                }
            }
        }        
    }
    
    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        Validate.notNull("messageLogFinder");
        Validate.notNull("publisher");
    }


	/* (non-Javadoc)
	 * @see gov.va.med.fw.batchprocess.AbstractLegacyDataProcess#executeProcess(gov.va.med.fw.batchprocess.DataProcessExecutionContext)
	 */
	protected void executeProcess(DataProcessExecutionContext context) throws Exception {
		int numberPublished = retransmit();
		context.getProcessStatistics().setNumberOfTotalRecords(numberPublished);
		context.getProcessStatistics().setNumberOfSuccessfulRecords(numberPublished);
	}
}
