

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


import gov.va.med.cds.hapi.HL7SupportInterface;
import gov.va.med.cds.logger.ApplicationLoggerInterface;
import gov.va.med.cds.logger.LogApplicationLogger;

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

import org.apache.commons.logging.LogFactory;


public class MappingResponseGenerator
    implements
        ResponseGeneratorInterface
{
    private static final String DEFAULT_RESPONSE_GENERATOR_KEY = "DEFAULT";
    
    /** Logger to be used by the data handler. */
    public ApplicationLoggerInterface appLogger = getLogger();
    /** Collection of response generators available for different message types*/
    private Map<String, ResponseGeneratorInterface> responseGeneratorMap = new HashMap<String, ResponseGeneratorInterface>();


    public String createResponse( HL7SupportInterface requestHl7Support, String response, String responseMessageControlId, Exception exception )
    {

        String messageType = DEFAULT_RESPONSE_GENERATOR_KEY;

        try
        {

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

        }
        catch ( Exception ex )
        {

            //Log the exception, but continue on with processing.
            appLogger.logMessage( "Error while parsing message for Sending Application and Message Type. ", ex );

        }

        ResponseGeneratorInterface responseGenerator = responseGeneratorMap.get( messageType );

        if ( responseGenerator == null )
        {
            //This is the case when message type is not supported by socket facade. Validation already failed.
            // We are going to use default response generator and sent error reply back 
            responseGenerator = responseGeneratorMap.get( DEFAULT_RESPONSE_GENERATOR_KEY );

        }

        return responseGenerator.createResponse( requestHl7Support, response, responseMessageControlId, exception );

    }


    public void setResponseGeneratorMap( Map<String, ResponseGeneratorInterface> responseGeneratorMap )
    {

        this.responseGeneratorMap = responseGeneratorMap;

    }


    ApplicationLoggerInterface getLogger( )
    {
        return new LogApplicationLogger( LogFactory.getLog( MappingResponseGenerator.class ) );
    }

}