package de.hsadmin.core.qserv;

import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;

import de.hsadmin.core.util.Config;

/**
 * An instance of this class is used to send Processor instances to the
 * QueueServer.
 * 
 * @author mi
 */
public class QueueClient extends QueueCommons {
	
	private QueueConnectionFactory jmsConnectionFactory;
	private Queue jmsSystemQueue;

	private QueueConnection jmsConnection;
	private QueueSession jmsSession;
	private QueueSender jmsSender;

	public QueueClient(QueueConnectionFactory jmsConFact, Queue jmsSysQueue)
			throws JMSException {
		this.jmsConnectionFactory = jmsConFact;
		this.jmsSystemQueue = jmsSysQueue;

		Config config = Config.getInstance();
		String jmsUser = config.getProperty("hsadmin.jms.username", "hsadmin");
		String jmsPass = config.getProperty("hsadmin.jms.password", "hsadmin-pw");
		jmsConnection = jmsConnectionFactory.createQueueConnection(jmsUser, jmsPass);
		jmsSession = jmsConnection.createQueueSession(DEFAULT, Session.AUTO_ACKNOWLEDGE);
		jmsSender = jmsSession.createSender(jmsSystemQueue);
	}

	// Query a single value from the QueueServer which will process it as
	// root.
	public void send(QueueTask task) throws ProcessorException {
		try {
			ObjectMessage jmsMessage = jmsSession.createObjectMessage(task);
			jmsSender.send(jmsMessage);
		} catch (JMSSecurityException secExc) {
			secExc.printStackTrace();
			throw new ProcessorException("Not allowed to send to queue "
					+ queueName(jmsSystemQueue) + " failed", secExc);
		} catch (Exception exc) {
			exc.printStackTrace();
			throw new ProcessorException("Error while sending to queue "
					+ queueName(jmsSystemQueue) + " failed", exc);
		}
	}

	private String queueName(Queue jmsSystemQueue2) {
		try {
			return jmsSystemQueue.getQueueName();
		} catch (Exception exc) {
			return "<unknown>";
		}
	}

	// frees all ressources
	public void close() {
		try {
			if (jmsSender != null) jmsSender.close();
		} catch (Exception exc) { }
		try {
			if (jmsSession != null) jmsSession.close();
		} catch (Exception exc) { }
		try {
			if (jmsConnection != null) jmsConnection.close();
		} catch (Exception exc) { }
	}
}
