

package gov.va.med.mediator.client.messagemediator;


import gov.va.med.mediator.exception.ConfigurationException;


/**
 * Handles the synchronous and asynchronous calls to CDS service.
 */

public class MessageMediatorDelegate
    implements
        MessageMediatorInterface
{

    private static final String SYNCHRONOUS_CHECK_MESSAGE = "Synchronous";
    private MessageMediatorInterface mediatorSynchronous;


    /*
     * (non-Javadoc)
     * @see gov.va.med.cds.client.messagemediator.MessageMediatorInterface#isAlive()
     */
    public boolean isAlive( )
    {
        boolean allNull = true;
        if ( mediatorSynchronous != null )
        {
            allNull = false;
            if ( !mediatorSynchronous.isAlive() )
                return false;
        }

        if ( allNull == true )
            throw new ConfigurationException( "The sub delegate dependencies need to be injected. None were. Please check the configuration" );

        return true;
    }


    /*
     * (non-Javadoc)
     * @see gov.va.med.cds.client.messagemediator.MessageMediatorInterface#processMessage(java.lang.String)
     */
    public String processMessage( String hl7MessageRequest )
    {
        return processMessage( hl7MessageRequest, false );
    }


    /*
     * (non-Javadoc)
     * @see gov.va.med.cds.client.messagemediator.MessageMediatorInterface#processMessage(java.lang.String, java.lang.Boolean)
     */
    public String processMessage( final String hl7MessageRequest, Boolean persistOriginalMessage )
    {
        checkConfiguration( mediatorSynchronous, SYNCHRONOUS_CHECK_MESSAGE );
        return mediatorSynchronous.processMessage( hl7MessageRequest, persistOriginalMessage );
    }


    /**
     * Spring DI related setter method for synchronous calls
     *
     * @param mediator message mediator object
     */
    public void setMessageMediator( MessageMediatorInterface mediator )
    {
        this.mediatorSynchronous = mediator;
    }


    private void checkConfiguration( Object delegate, String missingDelegate )
        throws ConfigurationException
    {
        if ( delegate == null )
        {
            throw new ConfigurationException( "The Message Mediator delegate " + missingDelegate
                            + " is missing and has not been injected - please check configuration." );
        }
    }

}
