/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.objectweb.jonas.mejb;

import java.rmi.RemoteException;

import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.j2ee.ListenerRegistration;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import org.objectweb.jonas.common.Log;
import org.objectweb.jonas.jmx.JmxService;
import org.objectweb.jonas.jmx.RMIConnector;
import org.objectweb.jonas.service.ServiceManager;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * ListenerRegistration implementation
 */
public class ListenerRegistrationImpl implements ListenerRegistration {
    transient Logger logger = null;

    // The ManagementListener MBean's object name
    ObjectName listenerMBean_on = null;

    // The initialization of transient attributes is completed on the client side
    boolean initialized = false;

    String proxyName = null;
    // The current MBean server's RMI connector name
    String rmiConnectorName = null;
    // Naming context used to bind the proxy object
    transient Context context = null;
    // Remote object called by the ManagementListenerMBean
    transient ListenerProxy proxy = null;

    /**
     * The constructor is executed on the server side.
     */
    public ListenerRegistrationImpl(ObjectName listenerMBean_on, String proxyName) {
        JmxService jmxService = null;
        try {
            jmxService = (JmxService) ServiceManager.getInstance().getJmxService();
        } catch (Exception e) {
            // should never occurs
        }
        rmiConnectorName = jmxService.getRmiConnectorName();
        this.listenerMBean_on = listenerMBean_on;
        this.proxyName = proxyName;
        logger = Log.getLogger("org.objectweb.jonas.management.j2eemanagement.event");
        logger.log(BasicLevel.INFO, "Create ListenerRegistration instance");
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "MBeanServer's RMI Connector: " + rmiConnectorName);
            logger.log(BasicLevel.DEBUG, "ManagementListener MBean object name: " +  listenerMBean_on.toString());
            logger.log(BasicLevel.DEBUG, "ListenerProxy JNDI name: " + proxyName);
        }
    }

    /**
     * Add a listener to a registered managed object.
     */
     public void addNotificationListener(ObjectName name,
                                        NotificationListener listener,
                                        NotificationFilter filter,
                                        Object handback)
        throws InstanceNotFoundException,
               RemoteException {

        // Create a naming context
        if (context == null) {
            try {
                context = new InitialContext();
            } catch (NamingException e) {
                // Could not create naming context
                throw new RemoteException("Could not register a listener to managed object " + name.toString());
            }
        }

        // Set actual listener and filter in the proxy
        if (proxy == null) {
            proxy = new ListenerProxyImpl();
            try {
                context.rebind(proxyName, proxy);
                System.out.println("ListenerRegistration.addNotificationListener: ListnerProxy created and binded in JNDI");
            } catch (NamingException e) {
                throw new RemoteException("Could not bind a listener proxy in JNDI:" + e.toString());
            }
        }

        RMIConnector rmic = null;
        try {
            rmic = (RMIConnector)PortableRemoteObject.narrow(context.lookup(rmiConnectorName), RMIConnector.class);
            if (rmic != null) {
                // Add a the ManagementListener MBean as listener to the 'name' MBean
                rmic.addNotificationListener(name, listenerMBean_on, null, handback);
                System.out.println("ListenerRegistration.addNotificationListener: ManagementListener MBean added as listener to managed object: " + name.toString());
            } else {
                throw new RemoteException("Could not add the ManagementListener MBean as listener to managed object: " + name.toString());
            }
        } catch (NamingException ne) {
            throw new RemoteException("Could not add the ManagementListener MBean as listener to managed object: " + name.toString() + " : " + ne.toString());
        }

        proxy.addNotificationListener(listener, filter);
    }

    /**
     * Enables to remove a listener from a registered managed object.
     */
    public void removeNotificationListener(ObjectName name,
                                        NotificationListener listener)
        throws InstanceNotFoundException,
               ListenerNotFoundException,
               RemoteException {

        proxy.removeNotificationListener(listener);

        if (context == null) {
            try {
                context = new InitialContext();
            } catch (NamingException e) {
                // Could not create naming context
                throw new RemoteException("Could not access registry to unbind the ListenerProxy");
            }
        }

        try {
            context.unbind(proxyName);
            System.out.println("ListenerRegistration.removeNotificationListener ListnerProxy un-bound from JNDI");
        } catch (NamingException e) {
            // Could not create naming context
            throw new RemoteException("Could not unbound ListenerProxy");
        }
    }
}
