package gov.va.med.pharmacy.jms.messaging;

import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessagePostProcessor;

import gov.va.med.pharmacy.ncpdpmsgs.MessageType;

public class InboundMsgProducer {

	
	private static final org.apache.logging.log4j.Logger LOG = org.apache.logging.log4j.LogManager.getLogger(InboundMsgProducer.class);
	
	@Autowired
	private JmsTemplate jmsTemplate;
	
	public void enqueueERxMessage(MessageType eRxMessage) throws Exception {

		try {
			
			LOG.info("Trying to enqueue incoming JMS message.");

			MessagePostProcessor mpp = new MessagePostProcessor() {
				
				public Message postProcessMessage(Message msg) throws JMSException {
					BytesMessage byteMessage = (BytesMessage) msg;
					
					byteMessage.reset();
					
					Long length = byteMessage.getBodyLength();
										
					byte[] newMessage = new byte[length.intValue()];
					int messageRead = byteMessage.readBytes(newMessage);
					
					LOG.debug("--- sending message", new String(newMessage));
					
					return msg;
				}
			};
			

			
			jmsTemplate.convertAndSend(eRxMessage,mpp);
						
//			System.out.println("Message sent");
			

		} catch (Exception e) {
			
			LOG.error("Error in enqueueERxMessage:"+e.getMessage());
			
			throw new Exception (e);
		}
	}	
}
