/** 
 * 
 * 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.Map;
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.message.ActiveMQDestination;
import org.activemq.message.ProducerInfo;
import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap;
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 MessageProducer advisories
 * 
 * * @version $Revision: 1.1.1.1 $
 */

public class ProducerAdvisor implements MessageListener {
    private static final Log log = LogFactory.getLog(ProducerAdvisor.class);
    private Connection connection;
    private ActiveMQDestination destination;
    private Session session;
    private List listeners = new CopyOnWriteArrayList();
    private SynchronizedBoolean started = new SynchronizedBoolean(false);
    private Map activeProducers = new ConcurrentHashMap();
    
    /**
     * Construct a ProducerAdvisor
     * @param connection
     * @param destination the destination to listen for Producer events
     * @throws JMSException
     */
    public ProducerAdvisor(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)) {
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(destination.getTopicForProducerAdvisory());
            consumer.setMessageListener(this);
        }
    }
    
    /**
     * stop listening for advisories
     * @throws JMSException
     */
    public void stop() throws JMSException{
        if (started.commit(true,false)){
            if (session != null){
                session.close();
            }
        }
    }
    
    /**
     * Add a listener
     * @param l
     */
    public void addListener(ProducerAdvisoryEventListener l){
        listeners.add(l);
    }
    
    /**
     * Remove a listener
     * @param l
     */
    public void removeListener(ProducerAdvisoryEventListener l){
        listeners.remove(l);
    }
    
    
    /**
     * returns true if there is an active producer for the destination
     * 
     * @param destination
     * @return true if a producer for the destination
     */
    public boolean isActive(Destination destination) {
        return activeProducers.containsKey(destination);
    }

    /**
     * return a set of active ProducerInfo's for a particular destination
     * @param destination
     * @return the set of ProducerInfo objects currently active
     */
    public Set activeProducers(Destination destination) {
        Set set = (Set) activeProducers.get(destination);
        return set != null ? set : new CopyOnWriteArraySet();
    }

    
    
    
    /**
     * OnMessage() implementation
     * @param msg
     */
    public void onMessage(Message msg){
        if (msg instanceof ObjectMessage){
            try {
                ProducerInfo info = (ProducerInfo)((ObjectMessage)msg).getObject();
                updateActiveProducers(info);
                ProducerAdvisoryEvent event = new ProducerAdvisoryEvent(info);
                fireEvent(event);
            }
            catch (JMSException e) {
                log.error("Failed to process message: " + msg);
            }
        }
    }
    
    private void fireEvent(ProducerAdvisoryEvent event){
        for (Iterator i = listeners.iterator(); i.hasNext(); ){
            ProducerAdvisoryEventListener l = (ProducerAdvisoryEventListener)i.next();
            l.onEvent(event);
        }
    }
    
    private void updateActiveProducers(ProducerInfo info) {
        Set set = (Set) activeProducers.get(info.getDestination());
        if (info.isStarted()) {
            if (set == null) {
                set = new CopyOnWriteArraySet();
                activeProducers.put(info.getDestination(), set);
            }
            set.add(info);
        }
        else {
            if (set != null) {
                set.remove(info);
                if (set.isEmpty()) {
                    activeProducers.remove(set);
                }
            }
        }
    }


}
