

package gov.va.med.cds.socket.server.handler;


import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.hapi.HL7SupportInterface;
import gov.va.med.mediator.client.messagemediator.MessageMediatorInterface;

import java.util.HashMap;
import java.util.Map;


public class MessageMediatorDispatcher
    implements
        MessageMediatorDispatcherInterface
{
    private Map<String, MessageMediatorInterface> messageTypeMediatorMap = new HashMap<String, MessageMediatorInterface>();


    public String dispatch( HL7SupportInterface hl7Support )
    {

        String response = null;

        try
        {

            String messageType = String.format( "%s~%s", hl7Support.getSendingApplication(), hl7Support.getMessageType() );

            MessageMediatorInterface messageMediator = messageTypeMediatorMap.get( messageType );

            if ( messageMediator == null )

            {
                // This is an extra layer of protection. This should never
                // happen,
                // validator should prevent this message from been processed
                throw new DispatchException( ErrorCodeEnum.DISPATCH_EXCEPTION, String.format(
                                "Unsupported message type '%s'. No mediator is defined for message.", messageType ) );

            }

            // The second parameter indicates to the message mediator whether the original
            // message should be persisted to the audit clob store or not. In the case of
            // a read message, this parameter is ignored. In the case of write messages
            // true causes the message to be persisted to the audit clob store. (vhaislegberb)
            response = messageMediator.processMessage( hl7Support.toEr7(), true );

        }
        catch ( Exception e )
        {
            // Catch any exception and wrap it into
            // MessageMediatorDispatcherException for later processing.
            String errorMessageToPassOn = e.getMessage();
            throw new DispatchException( ErrorCodeEnum.DISPATCH_EXCEPTION, String.format( "Error processing message. '%s'.", errorMessageToPassOn ) );
        }

        return response;
    }


    public void setMessageTypeMediatorMap( Map<String, MessageMediatorInterface> messageTypeMediatorMap )
    {

        this.messageTypeMediatorMap = messageTypeMediatorMap;

    }

}