/**
 * 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.BlazeMessageListener;
import org.apache.activeblaze.Subscription;
import org.apache.activeblaze.group.BlazeGroupChannel;
import org.apache.activeblaze.util.IdGenerator;

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

/**
 * Implementation of a JMS Connection
 */
public class BlazeJmsConnection implements Connection, TopicConnection, QueueConnection,
        org.apache.activeblaze.ExceptionListener {
    protected final BlazeGroupChannel channel;
    protected final IdGenerator tempDestinationGenerator = new IdGenerator("");
    private String clientId;
    private boolean clientIdSet;
    private ExceptionListener exceptionListener;
    private List<Session> sessions = new CopyOnWriteArrayList<Session>();
    private boolean closed;
    private int consumerMaxDispatchQueueDepth = 10000;

    protected BlazeJmsConnection(BlazeGroupChannel channel) {
        this.channel = channel;
        this.channel.setExceptionListener(this);
        this.clientId = channel.getName();
    }

    /**
     * @see javax.jms.Connection#close()
     */
    public void close() throws JMSException {
        this.closed = true;
        try {
            for (Session s : this.sessions) {
                s.close();
            }
            this.sessions.clear();
            this.channel.shutDown();
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    /**
     * @return ConnectionConsumer
     * @see javax.jms.Connection#createConnectionConsumer(javax.jms.Destination,
     *      java.lang.String, javax.jms.ServerSessionPool, int)
     */
    public ConnectionConsumer createConnectionConsumer(Destination destination, String messageSelector,
                                                       ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return ConnectionConsumer
     * @see javax.jms.Connection#createDurableConnectionConsumer(javax.jms.Topic,
     *      java.lang.String, java.lang.String, javax.jms.ServerSessionPool,
     *      int)
     */
    public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName,
                                                              String messageSelector, ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return Session
     * @see javax.jms.Connection#createSession(boolean, int)
     */
    public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
        checkClosed();
        int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode);
        Session result = new BlazeJmsSession(this, ackMode);
        addSession(result);
        return result;
    }

    /**
     * @return clientId
     * @see javax.jms.Connection#getClientID()
     */
    public String getClientID() {
        return this.clientId;
    }

    /**
     * @return ExceptionListener
     * @see javax.jms.Connection#getExceptionListener()
     */
    public ExceptionListener getExceptionListener() {
        return this.exceptionListener;
    }

    /**
     * @return ConnectionMetaData
     * @see javax.jms.Connection#getMetaData()
     */
    public ConnectionMetaData getMetaData() {
        return BlazeJmsConnectionMetaData.INSTANCE;
    }

    /**
     * @see javax.jms.Connection#setClientID(java.lang.String)
     */
    public void setClientID(String clientID) throws JMSException {
        if (this.channel.isStarted() && this.clientIdSet) {
            throw new IllegalStateException("The clientID has already been set");
        }
        if (clientID == null) {
            throw new IllegalStateException("Cannot have a null clientID");
        }
        this.clientId = clientID;
        this.clientIdSet = true;
        this.channel.setName(clientID);
    }

    /**
     * @see javax.jms.Connection#setExceptionListener(javax.jms.ExceptionListener)
     */
    public void setExceptionListener(ExceptionListener listener) {
        this.exceptionListener = listener;
    }

    /**
     * @see javax.jms.Connection#start()
     */
    public void start() throws JMSException {
        checkClosed();
        try {
            this.channel.start();
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    /**
     * @see javax.jms.Connection#stop()
     */
    public void stop() throws JMSException {
        checkClosed();
        try {
            this.channel.stop();
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    /**
     * @return ConnectionConsumer
     * @see javax.jms.TopicConnection#createConnectionConsumer(javax.jms.Topic,
     *      java.lang.String, javax.jms.ServerSessionPool, int)
     */
    public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector,
                                                       ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return TopicSession
     * @see javax.jms.TopicConnection#createTopicSession(boolean, int)
     */
    public TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException {
        checkClosed();
        int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode);
        TopicSession result = new BlazeJmsTopicSession(this, ackMode);
        addSession(result);
        return result;
    }

    /**
     * @return ConnectionConsumer
     * @see javax.jms.QueueConnection#createConnectionConsumer(javax.jms.Queue,
     *      java.lang.String, javax.jms.ServerSessionPool, int)
     */
    public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector,
                                                       ServerSessionPool sessionPool, int maxMessages) throws JMSException {
        checkClosed();
        return null;
    }

    /**
     * @return QueueSession
     * @see javax.jms.QueueConnection#createQueueSession(boolean, int)
     */
    public QueueSession createQueueSession(boolean transacted, int acknowledgeMode) throws JMSException {
        checkClosed();
        int ackMode = getSessionAcknowledgeMode(transacted, acknowledgeMode);
        QueueSession result = new BlazeJmsQueueSession(this, ackMode);
        addSession(result);
        return result;
    }

    /**
     * @see org.apache.activeblaze.ExceptionListener#onException(java.lang.Exception)
     */
    public void onException(Exception ex) {
        onException(BlazeJmsExceptionSupport.create(ex));
    }

    /**
     * @see org.apache.activeblaze.ExceptionListener#onException(java.lang.Exception)
     */
    public void onException(JMSException ex) {
        ExceptionListener l = this.exceptionListener;
        if (l != null) {
            l.onException(BlazeJmsExceptionSupport.create(ex));
        }
    }

    /**
     * @return the channel
     */
    protected BlazeGroupChannel getChannel() {
        return this.channel;
    }

    protected int getSessionAcknowledgeMode(boolean transacted, int acknowledgeMode) throws JMSException {
        int result = acknowledgeMode;
        if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED) {
            throw new JMSException("acknowledgeMode SESSION_TRANSACTED cannot be used for an non-transacted Session");
        }
        if (transacted) {
            result = Session.SESSION_TRANSACTED;
        }
        return result;
    }

    protected void removeSession(Session s) {
        this.sessions.remove(s);
    }

    protected void addSession(Session s) {
        this.sessions.add(s);
    }

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

    protected void addMesssageDispatcher(BlazeMessageListener consumer, Subscription s) throws JMSException {
        try {
            if (s.isTopic()) {
                this.channel.addBlazeTopicMessageListener(s, consumer);
            } else {
                this.channel.addBlazeQueueMessageListener(s, consumer);
            }
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    protected void removeMesssageDispatcher(BlazeMessageListener consumer, Subscription s) throws JMSException {
        try {
            if (s.isTopic()) {
                this.channel.removeBlazeTopicMessageListener(s, consumer);
            } else {
                this.channel.removeBlazeQueueMessageListener(s, consumer);
            }
        } catch (Exception e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    /**
     * Get the consumerMaxDispatchQueueDepth
     *
     * @return the consumerMaxDispatchQueueDepth
     */
    public int getConsumerMaxDispatchQueueDepth() {
        return this.consumerMaxDispatchQueueDepth;
    }

    /**
     * Set the consumerMaxDispatchQueueDepth
     *
     * @param consumerMaxDispatchQueueDepth the consumerMaxDispatchQueueDepth to set
     */
    public void setConsumerMaxDispatchQueueDepth(int consumerMaxDispatchQueueDepth) {
        this.consumerMaxDispatchQueueDepth = consumerMaxDispatchQueueDepth;
    }
}
