package com.javahonk.messaging;

import javax.annotation.PostConstruct;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.javahonk.interfaces.ITibcoPublisher;

/**
 * @author Java Honk
 *
 */
public class TibcoPublisher implements ITibcoPublisher {
	
	private static final Logger logger = LogManager.getLogger(TibcoPublisher.class.getName());


	private ConnectionFactory connectionFactorySPI;
	private String msgType;
	private String inputQueueName;
	
	private Connection connection;
	private Session session;
	private MessageProducer msgProducer;
		
	public TibcoPublisher(ConnectionFactory connectionFactorySPI,
			String msgType, 
			String inputQueueName) {
		this.connectionFactorySPI = connectionFactorySPI;
		this.msgType = msgType;
		this.inputQueueName = inputQueueName;
		
		logger.info("Tibco inputQueue: {}", inputQueueName);
		logger.info("Tibco msgType: {}", msgType);
	}
	
	@PostConstruct
	public void init() {
		
		try {
			connection = connectionFactorySPI.createConnection();			
			session = connectionFactorySPI.createSession(connection);
			
			Queue inputQueue = session.createQueue(inputQueueName);
			msgProducer = session.createProducer(inputQueue);
			
			connection.start();
			
		} catch (JMSException e) {
			logger.error("Error creating connection to tibco: {}", e);
		} 
	}

	@Override
	public void sendStockOrderToSPI(String stockOrder) {
		
		try {
			TextMessage msg = session.createTextMessage(stockOrder);
			msg.setJMSType(msgType);			
			
			msgProducer.send(msg);
			logger.info("Published Physical Settlement message : {}", stockOrder);
			
		} catch (JMSException e) {
			logger.error("Error sending Physical Settlement to input queue name:{} --> details exceptions: --> ", inputQueueName, e);
		}
		
	}	

}
