package gov.va.med.esr.messaging.service.outbound;

import gov.va.med.esr.common.model.lookup.MessageStatus;
import gov.va.med.esr.common.model.messaging.MessageLogEntry;
import gov.va.med.fw.hl7.InvalidMessageException;
import gov.va.med.fw.hl7.Message;
import gov.va.med.fw.service.ServiceException;
import gov.va.med.fw.util.builder.BuilderException;

/**
 * 
 * @author Rajiv Patnaik Created on Jul 14, 2006
 * @version 1.0
 * 
 * Copyright © 2006 VHA. All rights reserved
 */
public class SolicitatedAckOutboundProcessService extends
        AbstractOutboundProcessService implements OutboundProcessService
{

    /*
     * (non-Javadoc)
     * 
     * @see gov.va.med.esr.messaging.service.outbound.OutboundProcessService#processMessage(java.lang.Object)
     */
    public void processMessage(Object input) throws ServiceException
    {
        Object[] args = (Object[])input;

        this.processMessage((Message)args[0], (MessageLogEntry)args[1]);

    }

    /**
     * Send out a outbound ORF AE message in response to an error on the inbound QRY message
     *  
     * @param message
     * @param errorLogEntry
     * @throws ServiceException
     */
    public void processMessage(Message message, MessageLogEntry errorLogEntry)
            throws ServiceException
    {
        try
        {
            Message ackMessage = super.buildMessage(new Object[] { message,
                    errorLogEntry });

            if (super.logger.isDebugEnabled())
            {
                super.logger.debug(ackMessage.getMessageData());
            }

            MessageLogEntry ackLogEntry = super.createMessageLog(ackMessage, ackMessage
                    .getMessageID(), ackMessage.getMessageID(), null,
                    getLookupService().getVaFacilityByCode(message.getSendingFacility()), super
                            .buildTransmissionDate(message),MessageStatus.COMPLETE);   
            
            super.logMessage(ackLogEntry);

            super.logger.info("Built Solicitated Outbound Message Id " + ackMessage.getMessageID()
                    + " and message type " + this.getMessageTypeCode());
            
            if (super.logger.isDebugEnabled()) 
            {
                super.logger.debug("Batch Message: " + ackMessage.getMessageData());
            }
            
            super.publishMessage(ackMessage);
            
        } catch (BuilderException e)
        {
            throw new ServiceException("Failed to build outbound "
                    + this.getMessageTypeCode()
                    + " message due to an exception in processMessage", 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);
        }
    }

}