

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


import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import javax.interceptor.Interceptors;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.ejb.interceptor.SpringBeanAutowiringInterceptor;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jndi.JndiTemplate;

import gov.va.med.cds.hapi.HL7Utility;
import gov.va.med.repositories.fpds.ejb.config.BeanConstantsInterface;

@Interceptors(SpringBeanAutowiringInterceptor.class)
public abstract class AbstractBaseFpdsVistAMdb 
{
	
    protected final Log logger = LogFactory.getLog(getClass());
  
	protected JndiTemplate jndiTemplate = new JndiTemplate();
	protected String fpdsAppName = BeanConstantsInterface.FPDS_APP_NAME ;
	
	
	@Autowired
	@Qualifier(BeanConstantsInterface.ASYNC_RESPONSE_JMS_TEMPLATE)
	protected JmsTemplate responseJmsTemplate;
	
	@Autowired
	@Qualifier("hL7Utility")
	protected HL7Utility hL7Utility;
   
    
       
    public AbstractBaseFpdsVistAMdb() {
		
	}
    
          
    @SuppressWarnings( "unchecked" )
    protected Object safeGetEnvironmentEntry(String name, @SuppressWarnings( "rawtypes" ) Class type, Object defaultValue)
    {
        Object environmentEntry = defaultValue;
        try {
            environmentEntry =  this.jndiTemplate.lookup( name, type );
        } catch (NamingException ne)
        {
            logger.warn( String.format( "Error initializing FPDS MDB. Error Reason: %s", ne.getMessage() ), ne );
        }
        
        return environmentEntry;
    }

   
    protected void sendAckToDestination(final String responseMessage,
			final String responseRequestId, Destination defaultDestination) {
		
		responseJmsTemplate.send(defaultDestination,  new MessageCreator()
		{
			@Override
			public Message createMessage( Session session )
					throws JMSException
					{
						BytesMessage message = session.createBytesMessage();
						
						Charset charset = Charset.forName( "ISO-8859-1" );
			            ByteBuffer buffer = charset.encode( responseMessage );
						
						message.setJMSMessageID(responseRequestId);
						message.setJMSCorrelationID(responseRequestId);
						
						message.writeBytes( buffer.array() );
                     
						return message;
					}
		});
	}
    
}


