/*
 * 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 com.icesoft.net.messaging.Message;
import com.icesoft.net.messaging.MessageHandler;
import com.icesoft.net.messaging.MessageSelector;
import com.icesoft.net.messaging.ObjectMessage;
import com.icesoft.net.messaging.TextMessage;
import com.icesoft.net.messaging.expression.Container;
import com.icesoft.net.messaging.expression.Expression;
import com.icesoft.net.messaging.expression.Or;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jms.InvalidDestinationException;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import javax.servlet.ServletContext;

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

    private final Map<Topic, Expression> subscriberMap = new HashMap<Topic, Expression>();

    private TopicSubscriber topicSubscriber;
    private MessageReceiver messageReceiver;
    private ServletContext servletContext;

    private boolean started = false;

    public JMSSubscriberConnection(
        final Topic topic, final String userName, final String password, final JMSAdapter jmsAdapter,
        final ServletContext servletContext)
    throws IllegalArgumentException {
        super(topic, userName, password, jmsAdapter, Session.CLIENT_ACKNOWLEDGE);
        this.servletContext = servletContext;
    }

    public void addMessageHandler(final MessageHandler messageHandler) {
        if (messageHandler != null) {
            if (connected && messageReceiver != null) {
                synchronized (connectionLock) {
                    if (connected && messageReceiver != null) {
                        messageReceiver.getMessageListener().addMessageHandler(messageHandler);
                    }
                }
            }
        }
    }

    public void close()
    throws JMSException {
        if (connected) {
            synchronized (connectionLock) {
                if (connected) {
                    JMSException _jmsException = null;
                    if (started) {
                        try {
                            // throws JMSException.
                            stop();
                        } catch (JMSException exception) {
                            _jmsException = exception;
                        }
                    }
                    if (messageReceiver != null) {
                        messageReceiver.requestStop();
                        messageReceiver.getMessageListener().clearMessageHandlers();
                    }
                    if (topicSubscriber != null) {
                        try {
                            // throws JMSException.
                            topicSubscriber.close();
                        } catch (JMSException exception) {
                            if (_jmsException == null) {
                                _jmsException = exception;
                            }
                        }
                    }
                    try {
                        // throws JMSException.
                        super.close();
                    } catch (JMSException exception) {
                        if (_jmsException == null) {
                            _jmsException = exception;
                        }
                    }
                    messageReceiver = null;
                    topicSubscriber = null;
                    if (_jmsException != null) {
                        throw _jmsException;
                    }
                }
            }
        }
    }

    public void removeMessageHandler(final MessageHandler messageHandler) {
        if (messageHandler != null) {
            if (connected && messageReceiver != null) {
                synchronized (connectionLock) {
                    if (connected && messageReceiver != null) {
                        messageReceiver.getMessageListener().removeMessageHandler(messageHandler);
                    }
                }
            }
        }
    }

    public void start()
    throws JMSException {
        if (connected && !started) {
            synchronized (connectionLock) {
                if (connected && !started) {
                    topicConnection.start();
                    started = true;
                }
            }
        }
    }

    public void stop()
    throws JMSException {
        /*
         * Use of the stop() method on javax.jms.Connection
         * objects by applications in web and EJB containers may
         * interfere with the connection management functions of
         * the container and must not be used.
         */
        // do nothing.
        if (started) {
            synchronized (connectionLock) {
                if (started) {
//                    try {
//                        /*
//                         * IBM Websphere throws an IllegalArgumentException when
//                         * this stop() method is invoked.
//                         */
//                        // throws JMSException.
//                        topicConnection.stop();
//                    } catch (IllegalStateException exception) {
//                        // IBM Websphere: eat the exception.
////                        throw exception;
//                    } finally {
                        started = false;
//                    }
                }
            }
        }
    }

    public void subscribe(final MessageSelector messageSelector, final boolean noLocal)
    throws InvalidDestinationException, InvalidSelectorException, JMSException {
        if (connected) {
            synchronized (connectionLock) {
                if (connected) {
                    Container _container = new Container(messageSelector.getExpression());
                    if (subscriberMap.containsKey(topic)) {
                        subscriberMap.put(topic, new Or(subscriberMap.get(topic), _container));
                    } else {
                        subscriberMap.put(topic, _container);
                    }
                    if (topicSubscriber == null) {
                        // throws
                        //     InvalidDestinationException,
                        //     InvalidSelectorException, JMSException
                        topicSubscriber = topicSession.createSubscriber(topic, null, noLocal);
                        messageReceiver =
                            new MessageReceiver(new MessageListener(this, servletContext), topicSubscriber);
                        try {
                            // throws RejectedExecutionException
                            jmsAdapter.
                                getMessageServiceClient().getScheduledThreadPoolExecutor().execute(messageReceiver);
                        } catch (RejectedExecutionException exception) {
                            if (LOGGER.isLoggable(Level.SEVERE)) {
                                LOGGER.log(
                                    Level.SEVERE,
                                    "messageReceiver could not be accepted for execution!",
                                    exception);
                            }
                        }
                    }
                }
            }
        }
    }

    public void unsubscribe()
    throws JMSException {
        if (connected) {
            synchronized (connectionLock) {
                if (connected) {
                    if (messageReceiver != null) {
                        messageReceiver.requestStop();
                        messageReceiver.getMessageListener().clearMessageHandlers();
                    }
                    if (subscriberMap.containsKey(topic)) {
                        subscriberMap.remove(topic);
                    }
                    try {
                        if (topicSubscriber != null) {
                            // throws JMSException.
                            topicSubscriber.close();
                        }
                    } finally {
                        topicSubscriber = null;
                    }
                }
            }
        }
    }

    private boolean accept(final Message message) {
        return subscriberMap.containsKey(topic) && subscriberMap.get(topic).evaluate(message);
    }

    private static Message convert(final javax.jms.Message message, final ServletContext servletContext)
    throws JMSException {
        if (message instanceof javax.jms.TextMessage) {
            return convert((javax.jms.TextMessage)message, servletContext);
        } else if (message instanceof javax.jms.ObjectMessage) {
            return convert((javax.jms.ObjectMessage)message, servletContext);
        } else {
            return null;
        }
    }

    private static ObjectMessage convert(
        final javax.jms.ObjectMessage objectMessage, final ServletContext servletContext)
    throws JMSException {
        ObjectMessage _objectMessage = new ObjectMessage(objectMessage.getObject(), servletContext);
        copyProperties(objectMessage, _objectMessage);
        return _objectMessage;
    }

    private static TextMessage convert(
        final javax.jms.TextMessage textMessage, final ServletContext servletContext)
    throws JMSException {
        TextMessage _textMessage = new TextMessage(textMessage.getText(), servletContext);
        copyProperties(textMessage, _textMessage);
        return _textMessage;
    }

    private static void copyProperties(final javax.jms.Message source, final Message destination)
    throws JMSException {
        Enumeration _propertyNames = source.getPropertyNames();
        while (_propertyNames.hasMoreElements()) {
            String _propertyName = (String)_propertyNames.nextElement();
            destination.setObjectProperty(_propertyName, source.getObjectProperty(_propertyName));
        }
    }

    private class MessageListener
    implements javax.jms.MessageListener {
        private final Set<MessageHandler> messageHandlerSet = new CopyOnWriteArraySet<MessageHandler>();
        private final JMSSubscriberConnection jmsSubscriberConnection;
        private final ServletContext servletContext;

        private MessageListener(
            final JMSSubscriberConnection jmsSubscriberConnection, final ServletContext servletContext) {

            this.jmsSubscriberConnection = jmsSubscriberConnection;
            this.servletContext = servletContext;
        }

        public void onMessage(final javax.jms.Message message) {
            try {
                Message _message = convert(message, servletContext);
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(
                        Level.FINE,
                        "[" + jmsAdapter.getMessageServiceClient().getName() + "] Incoming message:\r\n\r\n" +
                            _message);
                }
                if (jmsSubscriberConnection.accept(_message)) {
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.log(
                            Level.FINE,
                            "[" + jmsAdapter.getMessageServiceClient().getName() + "] Accepted message:\r\n\r\n" +
                                _message);
                    }
                    for (MessageHandler _messageHandler : messageHandlerSet) {
                        MessageSelector _messageSelector = _messageHandler.getMessageSelector();
                        if (LOGGER.isLoggable(Level.FINE)) {
                            LOGGER.log(Level.FINE, "MessageHandler " + _messageHandler + ":\r\n" + _messageSelector);
                        }
                        if (_messageSelector == null || _messageSelector.matches(_message)) {
                            if (LOGGER.isLoggable(Level.FINE)) {
                                LOGGER.log(Level.FINE, "Match!");
                            }
                            _messageHandler.handle(_message);
                        }
                    }
                }
                message.acknowledge();
            } catch (JMSException exception) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(
                        Level.WARNING,
                        "Failed to convert message due to some internal error!",
                        exception);
                }
            }
        }

        private void addMessageHandler(final MessageHandler messageHandler) {
            if (messageHandler != null && !messageHandlerSet.contains(messageHandler)) {
                messageHandlerSet.add(messageHandler);
            }
        }

        private void clearMessageHandlers() {
            messageHandlerSet.clear();
        }

        private void removeMessageHandler(final MessageHandler messageHandler) {
            if (messageHandler != null && messageHandlerSet.contains(messageHandler)) {
                messageHandlerSet.remove(messageHandler);
            }
        }
    }

    private class MessageReceiver
    implements Runnable {
        private final MessageListener messageListener;
        private final TopicSubscriber topicSubscriber;

        private boolean stopRequested;

        private MessageReceiver(final MessageListener messageListener, final TopicSubscriber topicSubscriber) {
            this.messageListener = messageListener;
            this.topicSubscriber = topicSubscriber;
        }

        public void run() {
            try {
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE, this + " started.");
                }
                try {
                    while (!stopRequested) {
                        javax.jms.Message _message =
                            topicSubscriber.receive(jmsAdapter.getJMSProviderConfiguration().getReceiveTimeout());
                        if (_message != null) {
                            messageListener.onMessage(_message);
                        }
                    }
                } catch (JMSException exception) {
                    // reconnect will create a new instance of
                    // JMSSubscriberConnection.
                    jmsAdapter.
                        getMessageServiceClient().getAdministrator().reconnectNow();
                }
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.log(Level.FINE, this + " stopped.");
                }
            } catch (final Exception exception) {
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.log(
                        Level.WARNING, "Exception caught on " + this.getClass().getName() + " Runnable.", exception);
                }
            }
        }

        public String toString() {
            StringBuffer _string = new StringBuffer();
            _string.append("MessageReceiver [");
            try {
                _string.append(topicSubscriber.getMessageSelector());
            } catch (JMSException exception) {
                // Do nothing.
            }
            _string.append("]");
            return _string.toString();
        }

        private void requestStop() {
            stopRequested = true;
        }

        private MessageListener getMessageListener() {
            return messageListener;
        }

        private boolean isStopRequested() {
            return stopRequested;
        }
    }
}
