/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed 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.activemq.advisories;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.activemq.ActiveMQConnection;
import org.activemq.ActiveMQSession;
import org.activemq.message.ActiveMQDestination;
import EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList;
import EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArraySet;
import EDU.oswego.cs.dl.util.concurrent.SynchronizedBoolean;

/**
 * A helper class for listening for TempDestination advisories
 * 
 * @version $Revision: 1.1.1.1 $
 */
public class TempDestinationAdvisor implements MessageListener {
    private static final Log log = LogFactory.getLog(TempDestinationAdvisor.class);
    private Connection connection;
    private ActiveMQDestination destination;
    private Session session;
    private List listeners = new CopyOnWriteArrayList();
    private Set activeDestinations = new CopyOnWriteArraySet();
    private SynchronizedBoolean started = new SynchronizedBoolean(false);

    /**
     * Construct a TempDestinationAdvisor
     * 
     * @param connection
     * @param destination the destination to listen for TempDestination events
     * @throws JMSException
     */
    public TempDestinationAdvisor(Connection connection, Destination destination) throws JMSException {
        this.connection = connection;
        this.destination = ActiveMQDestination.transformDestination(destination);
    }

    /**
     * start listening for advisories
     * 
     * @throws JMSException
     */
    public void start() throws JMSException {
        if (started.commit(false, true)) {
            if (connection instanceof ActiveMQConnection) {
                session = ((ActiveMQConnection) connection).createSession(false, Session.AUTO_ACKNOWLEDGE, true);
                ((ActiveMQSession) session).setInternalSession(true);
            }
            else {
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            }
            MessageConsumer consumer = session.createConsumer(destination.getTopicForTempAdvisory());
            consumer.setMessageListener(this);
        }
    }

    /**
     * stop listening for advisories
     * 
     * @throws JMSException
     */
    public void stop() throws JMSException {
        if (started.commit(true, false)) {
            if (session != null) {
                session.close();
            }
        }
    }

    /**
     * returns true if the temporary destination is active
     * 
     * @param destination
     * @return true if a subscriber for the destination
     */
    public boolean isActive(Destination destination) {
        return activeDestinations.contains(destination);
    }

    /**
     * Add a listener
     * 
     * @param l
     */
    public void addListener(TempDestinationAdvisoryEventListener l) {
        listeners.add(l);
    }

    /**
     * Remove a listener
     * 
     * @param l
     */
    public void removeListener(TempDestinationAdvisoryEventListener l) {
        listeners.remove(l);
    }

    /**
     * OnMessage() implementation
     * 
     * @param msg
     */
    public void onMessage(Message msg) {
        if (msg instanceof ObjectMessage) {
            try {
                TempDestinationAdvisoryEvent event = (TempDestinationAdvisoryEvent) ((ObjectMessage) msg).getObject();
                if (event.isStarted()) {
                    activeDestinations.add(event.getDestination());
                }
                else {
                    activeDestinations.remove(event.getDestination());
                }
                fireEvent(event);
            }
            catch (JMSException e) {
                log.error("Failed to process message: " + msg);
            }
        }
    }

    private void fireEvent(TempDestinationAdvisoryEvent event) {
        for (Iterator i = listeners.iterator();i.hasNext();) {
            TempDestinationAdvisoryEventListener l = (TempDestinationAdvisoryEventListener) i.next();
            l.onEvent(event);
        }
    }
}