/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: BeanEventListener.java 19283 2010-02-24 16:16:26Z benoitf $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.cmi.internal.event;

import java.util.Iterator;
import java.util.Set;

import javax.ejb.EJBObject;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.cmi.controller.server.ServerClusterViewManager;
import org.ow2.cmi.info.CMIInfoExtractor;
import org.ow2.cmi.info.CMIInfoExtractorException;
import org.ow2.cmi.info.CMIInfoRepository;
import org.ow2.cmi.info.ClusteredObjectInfo;
import org.ow2.cmi.reference.CMIReference;
import org.ow2.cmi.reference.ServerRef;
import org.ow2.jonas.lib.util.Log;
import org.ow2.util.ee.event.listeners.AbsBeanEventListener;
import org.ow2.util.ee.event.types.BeanRegisterEvent;
import org.ow2.util.ee.event.types.BeanUnregisterEvent;
import org.ow2.util.event.api.IEvent;

/**
 * Listener for Beans events.
 * @author eyindanga
 */
public class BeanEventListener extends AbsBeanEventListener {
    /**
     * Event provider filter.
     */
    private static final String EVENT_PROVIDER_FILTER = "/beans/lifecycle/events";

    /**
     * Serial UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Logger for traces.
     */
    private static Logger cmilogger = Log.getLogger("org.ow2.jonas.cmi");

    /**
     * The clusterView manager.
     */
    private ServerClusterViewManager clusterViewManager = null;

    /**
     * Default constructor.
     */
    public BeanEventListener(final ServerClusterViewManager clusterViewManager) {
        super(EVENT_PROVIDER_FILTER);
        this.clusterViewManager = clusterViewManager;
    }

    /**
     * Handles the given event.
     * @param event the event to handle
     */
    @Override
    public void handle(final IEvent event) {
        try {
            if (BeanUnregisterEvent.class.isAssignableFrom(event.getClass())) {
                removeClusteredObject(((BeanUnregisterEvent) event).getJndiName());
            } else if (BeanRegisterEvent.class.isAssignableFrom(event.getClass())) {
                BeanRegisterEvent beanRegisterEvent = (BeanRegisterEvent) event;
                addClusteredObject(beanRegisterEvent.getJndiName(), beanRegisterEvent.getClusterConfig(),
                        beanRegisterEvent.getHomeClass(), beanRegisterEvent.getRemoteClass(),
                        beanRegisterEvent.getClassLoader(), beanRegisterEvent.isStateful(),
                        beanRegisterEvent.isClusterReplicated());
            } else {
                cmilogger.log(BasicLevel.DEBUG, "Unrecognized event type");
            }
        } catch (Exception e) {
            cmilogger.log(BasicLevel.ERROR, "Unable to handle event \n" + e);
        }

    }

    /**
     * Removes the given clustered object.
     * @param jndiName Name of the object to remove
     * @param clusterViewManager the server cluster view manager
     * @throws Exception any
     */
    public synchronized void removeClusteredObject(final String jndiName)
            throws Exception {
        cmilogger.log(BasicLevel.DEBUG, "Removing clustered object named :" + jndiName);
        if (CMIInfoRepository.containClusteredObjectInfo(jndiName)) {
            ServerRef serverRef = null;
            Set<String> protocols = clusterViewManager.getProtocols();
            for (Iterator<String> iterator = protocols.iterator(); iterator.hasNext();) {
                String proto = iterator.next();
                serverRef = clusterViewManager.getRefOnLocalRegistry(proto);
                CMIReference cmiReference = new CMIReference(serverRef, jndiName);
                try {
                    clusterViewManager.removeCMIReference(cmiReference);
                } catch (Exception e) {
                    cmilogger.log(BasicLevel.DEBUG, jndiName + "Not bound in the with protocol " + proto);
                }
            }
            CMIInfoRepository.removeClusteredObjectInfo(jndiName);
        }
    }

    /**
     * Add a clustered bean.
     * @param jndiName name of the bean
     * @param clusterConfig The cluster configuration
     * @param homeClass class of the home interface
     * @param remoteClass class of the remote interface
     * @param classLoader he classloader used by the container of this bean
     * @param stateful true if the bean has a state
     * @param clusterReplicated true if the bean is replicated (ha service is
     *        required)
     * @throws Exception any.
     */
    public synchronized void addClusteredObject(final String jndiName, final Object clusterConfig, final Class<?> homeClass,
            final Class<? extends EJBObject> remoteClass, final ClassLoader classLoader, final boolean stateful,
            final boolean clusterReplicated) throws Exception {
        if (clusterConfig != null) {
            try {
                ClusteredObjectInfo clusteredObjectInfo =
                    CMIInfoExtractor.extractClusteringInfoFromClusteredObject(clusterConfig,
                            homeClass, remoteClass, stateful, clusterReplicated, null);
                CMIInfoRepository.addClusteredObjectInfo(jndiName, clusteredObjectInfo);
                cmilogger.log(BasicLevel.INFO, "The object with name " + jndiName + " is clustered.");
            } catch (CMIInfoExtractorException e) {
                cmilogger.log(BasicLevel.ERROR, "Error when extracting infos about clustering for the object with name "
                        + jndiName, e);
                throw new Exception("Error when extracting infos about clustering for the object with name " + jndiName, e);
            }
        } else {
            cmilogger.log(BasicLevel.DEBUG, "Cluster configuration not set for the object : " + clusterConfig);
        }

    }

}
