/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activeblaze.jms;

import org.apache.activeblaze.wire.*;

import javax.jms.*;
import javax.jms.IllegalStateException;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * JMS Session implementation
 */
public class BlazeJmsSession implements Session, QueueSession, TopicSession {
    private final BlazeJmsConnection connection;
    private final int acknowledgementMode;
    private final List<MessageProducer> producers = new CopyOnWriteArrayList<MessageProducer>();
    private final List<MessageConsumer> consumers = new CopyOnWriteArrayList<MessageConsumer>();
    private MessageListener messageListener;
    private boolean closed;

    /**
     * Constructor
     */
    protected BlazeJmsSession(BlazeJmsConnection connection, int acknowledgementMode) {
        this.connection = connection;
        this.acknowledgementMode = acknowledgementMode;
    }

    /**
     * @see javax.jms.Session#close()
     */
    public void close() throws JMSException {
        this.closed = true;
        this.connection.removeSession(this);
        for (MessageConsumer c : this.consumers) {
            c.close();
        }
        this.consumers.clear();
    }

    /**
     * @see javax.jms.Session#commit()
     */
    public void commit() throws JMSException {
        checkClosed();
    }

    /**
     * @return QueueBrowser
     * @see javax.jms.Session#createBrowser(javax.jms.Queue)
     */
    public QueueBrowser createBrowser(Queue queue) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return QueueBrowser
     * @see javax.jms.Session#createBrowser(javax.jms.Queue, java.lang.String)
     */
    public QueueBrowser createBrowser(Queue queue, String messageSelector) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return BytesMessage
     * @see javax.jms.Session#createBytesMessage()
     */
    public BytesMessage createBytesMessage() throws IllegalStateException {
        checkClosed();
        return new BlazeJmsBytesMessage();
    }

    /**
     * @return a MessageConsumer
     * @see javax.jms.Session#createConsumer(javax.jms.Destination)
     */
    public MessageConsumer createConsumer(Destination destination) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(destination);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsMessageConsumer result = new BlazeJmsMessageConsumer(this, dest, queueDepth);
        add(result);
        return result;
    }

    /**
     * @return MessageConsumer
     * @see javax.jms.Session#createConsumer(javax.jms.Destination, java.lang.String)
     */
    public MessageConsumer createConsumer(Destination destination, String messageSelector) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(destination);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsMessageConsumer result = new BlazeJmsMessageConsumer(this, dest, queueDepth);
        result.setMessageSelector(messageSelector);
        add(result);
        return result;
    }

    /**
     * @return the MessageConsumer
     * @see javax.jms.Session#createConsumer(javax.jms.Destination, java.lang.String, boolean)
     */
    public MessageConsumer createConsumer(Destination destination, String messageSelector, boolean NoLocal)
            throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(destination);

        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsTopicSubscriber result = new BlazeJmsTopicSubscriber(this, dest, "", false, NoLocal, queueDepth);
        result.setMessageSelector(messageSelector);
        add(result);
        return result;
    }

    /**
     * @return a TopicSubscriber
     * @see javax.jms.Session#createDurableSubscriber(javax.jms.Topic, java.lang.String)
     */
    public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(topic);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsTopicSubscriber result = new BlazeJmsTopicSubscriber(this, dest, "", true, false, queueDepth);
        add(result);
        return result;
    }

    /**
     * @return TopicSubscriber
     * @see javax.jms.Session#createDurableSubscriber(javax.jms.Topic, java.lang.String, java.lang.String, boolean)
     */
    public TopicSubscriber createDurableSubscriber(Topic topic, String name, String messageSelector, boolean noLocal)
            throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(topic);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsTopicSubscriber result = new BlazeJmsTopicSubscriber(this, dest, "", true, noLocal, queueDepth);
        result.setMessageSelector(messageSelector);
        add(result);
        return result;
    }

    /**
     * @return MapMessage
     * @see javax.jms.Session#createMapMessage()
     */
    public MapMessage createMapMessage() throws IllegalStateException {
        checkClosed();
        return new BlazeJmsMapMessage();
    }

    /**
     * @return Message
     * @see javax.jms.Session#createMessage()
     */
    public Message createMessage() throws IllegalStateException {
        checkClosed();
        return new BlazeJmsMessage();
    }

    /**
     * @return ObjectMessage
     * @see javax.jms.Session#createObjectMessage()
     */
    public ObjectMessage createObjectMessage() throws IllegalStateException {
        checkClosed();
        return new BlazeJmsObjectMessage();
    }

    /**
     * @return ObjectMessage
     * @see javax.jms.Session#createObjectMessage(java.io.Serializable)
     */
    public ObjectMessage createObjectMessage(Serializable object) throws JMSException {
        checkClosed();
        ObjectMessage result = createObjectMessage();
        result.setObject(object);
        return result;
    }

    /**
     * @return MessageProducer
     * @see javax.jms.Session#createProducer(javax.jms.Destination)
     */
    public MessageProducer createProducer(Destination destination) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(destination);
        BlazeJmsMessageProducer result = new BlazeJmsMessageProducer(this, dest);
        add(result);
        return result;
    }

    /**
     * @return Queue
     * @see javax.jms.Session#createQueue(java.lang.String)
     */
    public Queue createQueue(String queueName) throws JMSException {
        checkClosed();
        return new BlazeJmsQueue(queueName);
    }

    /**
     * @return StreamMessage
     * @see javax.jms.Session#createStreamMessage()
     */
    public StreamMessage createStreamMessage() throws JMSException {
        checkClosed();
        return new BlazeJmsStreamMessage();
    }

    /**
     * @return TemporaryQueue
     * @see javax.jms.Session#createTemporaryQueue()
     */
    public TemporaryQueue createTemporaryQueue() throws JMSException {
        checkClosed();
        return new BlazeJmsTempQueue(this.connection.tempDestinationGenerator.generateId());
    }

    /**
     * @return TemporaryTopic
     * @see javax.jms.Session#createTemporaryTopic()
     */
    public TemporaryTopic createTemporaryTopic() throws JMSException {
        checkClosed();
        return new BlazeJmsTempTopic(this.connection.tempDestinationGenerator.generateId());
    }

    /**
     * @return TextMessage
     * @see javax.jms.Session#createTextMessage()
     */
    public TextMessage createTextMessage() throws JMSException {
        checkClosed();
        return new BlazeJmsTextMessage();
    }

    /**
     * @return TextMessage
     * @see javax.jms.Session#createTextMessage(java.lang.String)
     */
    public TextMessage createTextMessage(String text) throws JMSException {
        checkClosed();
        BlazeJmsTextMessage result = new BlazeJmsTextMessage();
        result.setText(text);
        return result;
    }

    /**
     * @return Topic
     * @see javax.jms.Session#createTopic(java.lang.String)
     */
    public Topic createTopic(String topicName) throws JMSException {
        checkClosed();
        return new BlazeJmsTopic(topicName);
    }

    /**
     * @return acknowledgeMode
     * @see javax.jms.Session#getAcknowledgeMode()
     */
    public int getAcknowledgeMode() throws JMSException {
        checkClosed();
        return this.acknowledgementMode;
    }

    /**
     * @see javax.jms.Session#getMessageListener()
     */
    public MessageListener getMessageListener() throws JMSException {
        checkClosed();
        return this.messageListener;
    }

    /**
     * @see javax.jms.Session#getTransacted()
     */
    public boolean getTransacted() throws JMSException {
        checkClosed();
        return this.acknowledgementMode == Session.SESSION_TRANSACTED;
    }

    /**
     * @see javax.jms.Session#recover()
     */
    public void recover() throws JMSException {
        checkClosed();
    }

    /**
     * @see javax.jms.Session#rollback()
     */
    public void rollback() throws JMSException {
        checkClosed();
    }

    /**
     * @see javax.jms.Session#run()
     */
    public void run() {
        // TODO Auto-generated method stub
    }

    /**
     * @see javax.jms.Session#setMessageListener(javax.jms.MessageListener)
     */
    public void setMessageListener(MessageListener listener) throws JMSException {
        checkClosed();
        this.messageListener = listener;
    }

    /**
     * @see javax.jms.Session#unsubscribe(java.lang.String)
     */
    public void unsubscribe(String name) throws JMSException {
        checkClosed();
    }

    /**
     * @return QueueRecevier
     * @see javax.jms.QueueSession#createReceiver(javax.jms.Queue)
     */
    public QueueReceiver createReceiver(Queue queue) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(queue);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsQueueReceiver result = new BlazeJmsQueueReceiver(this, dest, queueDepth);
        add(result);
        return result;
    }

    /**
     * @return QueueReceiver
     * @see javax.jms.QueueSession#createReceiver(javax.jms.Queue, java.lang.String)
     */
    public QueueReceiver createReceiver(Queue queue, String messageSelector) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(queue);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsQueueReceiver result = new BlazeJmsQueueReceiver(this, dest, queueDepth);
        result.setMessageSelector(messageSelector);
        add(result);
        return result;
    }

    /**
     * @return QueueSender
     * @see javax.jms.QueueSession#createSender(javax.jms.Queue)
     */
    public QueueSender createSender(Queue queue) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(queue);
        BlazeJmsQueueSender result = new BlazeJmsQueueSender(this, dest);
        return result;
    }

    /**
     * @return TopicPublisher
     * @see javax.jms.TopicSession#createPublisher(javax.jms.Topic)
     */
    public TopicPublisher createPublisher(Topic topic) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(topic);
        BlazeJmsTopicPublisher result = new BlazeJmsTopicPublisher(this, dest);
        add(result);
        return result;
    }

    /**
     * @return TopicSubscriber
     * @see javax.jms.TopicSession#createSubscriber(javax.jms.Topic)
     */
    public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(topic);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsTopicSubscriber result = new BlazeJmsTopicSubscriber(this, dest, "", false, false, queueDepth);
        add(result);
        return result;
    }

    /**
     * @return TopicSubscriber
     * @see javax.jms.TopicSession#createSubscriber(javax.jms.Topic, java.lang.String, boolean)
     */
    public TopicSubscriber createSubscriber(Topic topic, String messageSelector, boolean noLocal) throws JMSException {
        checkClosed();
        BlazeJmsDestination dest = BlazeJmsDestination.transform(topic);
        int queueDepth = this.connection.getConsumerMaxDispatchQueueDepth();
        BlazeJmsTopicSubscriber result = new BlazeJmsTopicSubscriber(this, dest, "", false, noLocal, queueDepth);
        result.setMessageSelector(messageSelector);
        return result;
    }

    protected void add(BlazeJmsMessageConsumer consumer) throws JMSException {
        this.consumers.add(consumer);
        this.connection.addMesssageDispatcher(consumer, consumer.getSubscription());
    }

    protected void remove(BlazeJmsMessageConsumer consumer) throws JMSException {
        this.consumers.remove(consumer);
        this.connection.removeMesssageDispatcher(consumer, consumer.getSubscription());
    }

    protected void add(MessageProducer producer) {
        this.producers.add(producer);
    }

    protected void remove(MessageProducer producer) {
        this.producers.remove(producer);
    }

    protected void onException(Exception ex) {
        this.connection.onException(ex);
    }

    /**
     * @see org.apache.activeblaze.ExceptionListener#onException(java.lang.Exception)
     */
    protected void onException(JMSException ex) {
        this.connection.onException(ex);
    }

    protected void send(Destination dest, Message msg, int deliveryMode, int priority, long timeToLive)
            throws JMSException {
        BlazeJmsDestination destination = BlazeJmsDestination.transform(dest);
        BlazeJmsMessage message = BlazeJmsMessageTransformation.transformMessage(msg);
        send(destination, message, deliveryMode, priority, timeToLive);
    }

    private void send(BlazeJmsDestination destination, BlazeJmsMessage message, int deliveryMode, int priority,
                      long timeToLive) throws JMSException {
        message.setJMSDestination(destination);
        message.setJMSDeliveryMode(deliveryMode);
        message.setJMSPriority(priority);
        if (timeToLive > 0) {
            long timeStamp = System.currentTimeMillis();
            message.setTimeStamp(timeStamp);
            message.setExpiration(System.currentTimeMillis() + timeToLive);
        }
        try {
            if (destination.isTopic()) {
                this.connection.channel.broadcast(destination.getDestination(), message);
            } else {
                this.connection.channel.send(destination.getDestination(), message);
            }
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    protected void checkClosed() throws IllegalStateException {
        if (this.closed) {
            throw new IllegalStateException("The MessageProducer is closed");
        }
    }
}
