/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */
package com.icesoft.net.messaging.jms;

import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicSession;

public abstract class AbstractJMSConnection
implements JMSConnection {
    private static final Logger LOGGER = Logger.getLogger(AbstractJMSConnection.class.getName());

    protected final Object connectionLock = new Object();

    protected JMSAdapter jmsAdapter;

    protected Topic topic;
    protected String userName;
    protected String password;
    protected TopicConnection topicConnection;
    protected TopicSession topicSession;
    protected int acknowledgeMode;

    protected boolean connected = false;

    protected AbstractJMSConnection(
        final Topic topic, final String userName, final String password, final JMSAdapter jmsAdapter,
        final int acknowledgeMode)
    throws IllegalArgumentException {
        if (topic == null) {
            throw new IllegalArgumentException("topic is null");
        }
        if (jmsAdapter == null) {
            throw new IllegalArgumentException("jmsAdapter is null");
        }
        this.topic = topic;
        this.userName = userName;
        this.password = password;
        this.jmsAdapter = jmsAdapter;
        this.acknowledgeMode = acknowledgeMode;
    }

    public void close()
    throws JMSException {
        if (connected) {
            synchronized (connectionLock) {
                if (connected) {
                    JMSException _jmsException = null;
                    try {
                        if (topicSession != null) {
                            // throws JMSException.
                            topicSession.close();
                        }
                    } catch (JMSException exception) {
                        _jmsException = exception;
                    }
                    try {
                        if (topicConnection != null) {
                            // throws JMSException.
                            topicConnection.close();
                        }
                    } catch (JMSException exception) {
                        if (_jmsException == null) {
                            _jmsException = exception;
                        }
                    }
                    topicSession = null;
                    topicConnection = null;
                    connected = false;
                    if (_jmsException != null) {
                        throw _jmsException;
                    }
                }
            }
        }
    }

    public void open()
    throws JMSException, JMSSecurityException {
        if (!connected) {
            synchronized (connectionLock) {
                if (!connected) {
                    if (userName != null && password != null) {
                        topicConnection =
                            jmsAdapter.getTopicConnectionFactory().
                                createTopicConnection(userName, password);
                    } else {
                        topicConnection =
                            jmsAdapter.getTopicConnectionFactory().
                                createTopicConnection();
                    }
                    topicSession = topicConnection.createTopicSession(false, acknowledgeMode);
                    connected = true;
                }
            }
        }
    }

    protected static String toString(final javax.jms.Message message) {
        StringBuffer _messageString = new StringBuffer();
        try {
            Enumeration _propertyNames = message.getPropertyNames();
            while (_propertyNames.hasMoreElements()) {
                String _propertyName = (String)_propertyNames.nextElement();
                _messageString.
                    append(_propertyName).append(": ").append(message.getObjectProperty(_propertyName)).append("\r\n");
            }
            _messageString.append("\r\n");
            if (message instanceof javax.jms.ObjectMessage) {
                _messageString.append(((javax.jms.ObjectMessage)message).getObject());
            } else if (message instanceof javax.jms.TextMessage) {
                _messageString.append(((javax.jms.TextMessage)message).getText());
            }
            _messageString.append("\r\n");
        } catch (JMSException exception) {
            // do nothing (this is just a toString() method)
        }
        return _messageString.toString();
    }
}
