/**
 * 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.BlazeMessage;
import org.apache.activeblaze.BlazeMessageListener;
import org.apache.activeblaze.Subscription;
import org.apache.activeblaze.wire.BlazeJmsMessage;
import org.apache.activeblaze.wire.BlazeJmsMessageTransformation;

import javax.jms.IllegalStateException;
import javax.jms.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * implementation of a Jms Message Consumer
 */
public class BlazeJmsMessageConsumer implements MessageConsumer, BlazeMessageListener {
    protected final BlazeJmsSession session;
    protected final BlazeJmsDestination destination;
    protected final Subscription subscription = new Subscription();
    private boolean closed;
    private MessageListener messageListener;
    private String messageSelector = "";
    private final Lock lock = new ReentrantLock();
    private LinkedBlockingQueue<BlazeJmsMessage> dispatchQueue;

    protected BlazeJmsMessageConsumer(BlazeJmsSession s, BlazeJmsDestination destination, int queueDepth) {
        this.session = s;
        this.destination = destination;
        this.subscription.setDestination(this.destination.getDestination());
        this.dispatchQueue = new LinkedBlockingQueue<BlazeJmsMessage>(queueDepth);
    }

    /**
     * @see javax.jms.MessageConsumer#close()
     */
    public void close() throws JMSException {
        this.closed = true;
        this.session.remove(this);
    }

    protected Subscription getSubscription() {
        return this.subscription;
    }

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

    /**
     * @return the Message Selector
     * @see javax.jms.MessageConsumer#getMessageSelector()
     */
    public String getMessageSelector() throws JMSException {
        checkClosed();
        return this.messageSelector;
    }

    /**
     * @return a Message or null if closed during the operation
     * @see javax.jms.MessageConsumer#receive()
     */
    public Message receive() throws JMSException {
        checkClosed();
        return this.dispatchQueue.poll();
    }

    /**
     * @return a MEssage or null
     * @see javax.jms.MessageConsumer#receive(long)
     */
    public Message receive(long timeout) throws JMSException {
        checkClosed();
        try {
            return this.dispatchQueue.poll(timeout, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw BlazeJmsExceptionSupport.create(e);
        }
    }

    /**
     * @return a Message or null
     * @see javax.jms.MessageConsumer#receiveNoWait()
     */
    public Message receiveNoWait() throws JMSException {
        checkClosed();
        Message result = this.dispatchQueue.peek();
        if (result != null) {
            this.dispatchQueue.remove(result);
        }
        return result;
    }

    /**
     * @see javax.jms.MessageConsumer#setMessageListener(javax.jms.MessageListener)
     */
    public void setMessageListener(MessageListener listener) throws JMSException {
        checkClosed();
        this.lock.lock();
        try {
            this.messageListener = listener;
            if (!this.dispatchQueue.isEmpty() && this.messageListener != null) {
                List<BlazeJmsMessage> drain = new ArrayList<BlazeJmsMessage>(this.dispatchQueue.size());
                this.dispatchQueue.drainTo(drain);
                for (BlazeJmsMessage m : drain) {
                    this.messageListener.onMessage(m);
                }
                drain.clear();
            }
        } finally {
            this.lock.unlock();
        }
    }

    /**
     * @param messageSelector the messageSelector to set
     */
    public void setMessageSelector(String messageSelector) throws IllegalStateException {
        checkClosed();
        this.messageSelector = messageSelector;
    }

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

    /**
     * @param message
     */
    public void onMessage(BlazeJmsMessage message) {
        this.lock.lock();
        try {
            if (this.messageListener != null) {
                this.messageListener.onMessage(message);
            } else {
                this.dispatchQueue.add(message);
            }
        } finally {
            lock.unlock();
        }
    }

    public void onMessage(BlazeMessage message) {
        this.lock.lock();
        try {
            BlazeJmsMessage result = BlazeJmsMessageTransformation.transformMessage(message);
            if (this.messageListener != null) {
                this.messageListener.onMessage(result);
            } else {
                this.dispatchQueue.add(result);
            }
        } catch (JMSException e) {
            this.session.onException(e);
        } finally {
            this.lock.unlock();
        }
    }
}
