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

//Framework Classes
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.util.builder.BuilderException;
import gov.va.med.fw.hl7.InvalidMessageException;
import gov.va.med.fw.hl7.Message;

//ESR Classes
import gov.va.med.esr.common.model.messaging.MessageLogEntry;
import gov.va.med.esr.common.model.lookup.VAFacility;
import gov.va.med.esr.common.model.ee.EGTSetting;

/**
 * Class to process MFNZEG message.
 * 
 * @author Alex Yoon
 * @version 1.0
 */
public class MFNZEGProcessService extends AbstractOutboundProcessService
	implements OutboundMessageMasterFileService {

    /**
     * Default constructor.
l */
    public MFNZEGProcessService()
    {
        super();
    }
    
    public void processMessage(Object obj, VAFacility site) throws ServiceException {
        this.processMessage(obj, site, null);
    }
    
    public void processMessage(Object obj, VAFacility site, MessageLogEntry log) throws ServiceException {
        try
        {
            if ((obj == null) || !(obj instanceof EGTSetting)) {
                throw new ServiceException("Invalid input parameter to build a MFNZEG message.");
            }
            
            Message message = super.buildMessage(new Object[] {
                    (EGTSetting)obj, site });
            
            MessageLogEntry logEntry;
            //If normal outbound message.
            if (log == null) {
                
                String egtSetttingId = ((EGTSetting) obj).getEntityKey() == null ? null
                        : ((EGTSetting) obj).getEntityKey()
                                .getKeyValueAsString();
                
	            logEntry = super.createMessageLog(message,
	                    message.getMessageID(), message.getMessageID(), null,
	                    site, super.buildTransmissionDate(message),egtSetttingId);
            }
            else {	//If retransmisstion.
                logEntry = super.createMessageLog(message,
                        message.getMessageID(), message.getMessageID(), null,
	                    site, super.buildTransmissionDate(message),
	                    log.getRetransmissionCount() + 1,
	                    log);
            }
            
            super.logMessage(logEntry);
            
            super.publishMessage(message);
            
        }
        catch(BuilderException e)
        {
            throw new ServiceException(
                    "Failed to build MFNZEG message due to an exception", e);
        }
        catch(InvalidMessageException e)
        {
            //ASSERT: Should not happen if the message is already parsed.
            throw new RuntimeException(
                    "Failed to obtain data from the message", e);
        }
    }
}
