

package gov.va.med.repositories.fpds.ejb;


import java.nio.ByteBuffer;

import javax.interceptor.Interceptors;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;

import gov.va.med.cds.hapi.HL7SupportHAPI;
import gov.va.med.cds.hapi.HL7SupportInterface;

@Interceptors(SpringBeanAutowiringInterceptor.class)
public class FpdsVistAHl7AckResponseMdb extends AbstractBaseFpdsVistAMdb
implements MessageListener   
{
          
    public FpdsVistAHl7AckResponseMdb() {
		
	}
    
          
    /* (non-Javadoc)
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    public void onMessage( Message message )
    {
    	HL7SupportInterface hl7Support = null;  
        String responseDestinationJndiName = null;
        String hl7AckResponse = null;
        
        try
        {
            byte[] messageBytes = null;
                		
            if ( message instanceof BytesMessage )
            {
                BytesMessage bytesMsg = ( BytesMessage )message;
                int msgLength = ( int )bytesMsg.getBodyLength();
                messageBytes = new byte[msgLength];
                bytesMsg.readBytes( messageBytes );
            }
            else if ( message instanceof TextMessage )
            {
                TextMessage textMsg = ( TextMessage )message;
                messageBytes = textMsg.getText().getBytes();
            }

            //get the Hl7 ACK response and configure the hl7Support to assist processing
            ByteBuffer messageBuffer = ByteBuffer.wrap( messageBytes );
            hl7AckResponse = new String( messageBuffer.array() );
            hl7Support = HL7SupportHAPI.createTranslationSupport( hl7AckResponse );
                       
            //ACK responses return with the Original sendingApplication (MSH-3) reversed and now populated as the receivingApplication (MSH-5)
            responseDestinationJndiName = hL7Utility.getSendingApplicaionDestination(hl7Support.getReceivingApplication());
            
        	if(hl7AckResponse != null )
        	{
        		try {
                       	
        			final String responseMessage = hl7AckResponse;
        			final String responseRequestId = hl7Support.getAckOriginalMessageControlId();
        		
        			//get intended client destination
        			InitialContext context = new InitialContext();
        			Destination destination = null;
        			try{
        				destination = (Destination)context.lookup(responseDestinationJndiName);
        			}
        			catch(Exception ee){
        				//The receiving application name in MSH 5 was Unknown - the DNS name was not located
        				String errMsg = "Failed to resolve the JNDI name for the JMS response destination - could not send ack response: " + responseMessage;
        				logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, responseRequestId, fpdsAppName ,errMsg ), ee );
        			}
        			        	
        			if(destination != null){
        				try{
        					sendAckToDestination(responseMessage, responseRequestId, destination);
        				}catch(Exception ex1){
        					//can't resolve destination by name - only option is to send it to default destination.
        					String errMsg = "Failed to resolve the response JMS destination - could not send ack response: " + responseMessage;
        	        		logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, responseRequestId, fpdsAppName, errMsg ), ex1 );
        				}
                     }
                           			
        		} 
        		catch (Exception ex2) {
        			String errMsg = "Failed to publish response message ACK to a JMS destination - could not send ack response: " + hl7AckResponse;
        			logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, hl7Support.getAckOriginalMessageControlId(), fpdsAppName, errMsg ), ex2 );
        			//unable to send ACK - incoming message does not have response information populated in MSH - will NOT re-throw error because that would place message on the errorQ - we don't want any messages to go to errorQ
        		}
        	}   
        }
        catch ( Exception e )
        {
        	String errMsg = "Failed to extract and publish response message ACK to a JMS destination - could not send ack response: " + hl7AckResponse;
        	//FortifyScan Null Deference fix
        	if(logger != null && hl7Support != null){
        		logger.error( gov.va.med.cds.util.LogMessageUtil.buildMessage( null, hl7Support.getAckOriginalMessageControlId(), fpdsAppName, errMsg ), e );
				//unable to send ACK - error extracting Hl7Act from JMS or some unknown error - will NOT re-throw error because that would place message on the errorQ - we don't want any messages to go to the errorQ
        	}      
        }
      
    }
    
    
}


