/**
 * 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.management;

// JMX import
import javax.management.ListenerNotFoundException;
import javax.management.MBeanNotificationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This MBean implementation has to be extended by MBeans associated to reconfigurable JOnAS services
 * and to reconfigurable resources managed by JOnAS (DataSources and MailFactories).
 * These MBeans can add and remove a notification listener, and emit notifications towards this listener.
 * Currently only one listner may register as listener: the ReconfigManager MBean created at the server start-up.
 * @author Adriana Danes
 * Contributor(s):
 */
public class ReconfigDispatcher extends NotificationBroadcasterSupport implements ReconfigDispatcherMBean {

    private static Logger slogger = null;

    /**
     * Management notification type for <i>reconfiguration</i> events (notify that the management application made a reconfiguration operation)
     */
    public static final String RECONFIG_TYPE = "jonas.management.reconfiguration";
    /**
     * Management notification type for <i>save configuration</i> events (notify that the management application asks for save changes)
     */
    public static final String SAVE_RECONFIG_TYPE = "jonas.management.reconfiguration.save";
    /**
     * Class implementing the management notifications.
     */
    final String RECONFIG_NOTIF_CLASS = "jmx.management.Notification";
    final String SAVE_RECONFIG_NOTIF_CLASS = "jmx.management.Notification";

    /**
     * There may be only one listener : the ReconfigManager MBean.
     */
    ListenerJavaBean myListener = null;

    /**
     * Initialize the logger with a Logger provided by the reconfigurable resource
     * or service.
     * @param mylogger the logger provided by a sub-class
     */
    public void initLogger(Logger mylogger) {
        slogger = mylogger;
    }

    /**
     * This method is called by the ReconfigManager.
     * @listner  the ReconfigManager
     * @filter   null (not used)
     * @handback null (not used
     */
    public void addNotificationListener(NotificationListener listner,
                                        NotificationFilter filter,
                                        java.lang.Object handback)
        throws java.lang.IllegalArgumentException {

        if (slogger.isLoggable(BasicLevel.DEBUG)) {
            slogger.log(BasicLevel.DEBUG, "handback: " + handback);
            if (myListener == null) {
                slogger.log(BasicLevel.DEBUG, "Register the listener");
            } else {
                slogger.log(BasicLevel.DEBUG, "Caution : Re-register a listener !!! ");
            }
        }
        myListener = new ListenerJavaBean(listner, filter, handback);
    }
    /**
     * This method is called by the ReconfigManager when it no longer needs to receive management notifications.
     * @listner the ReconfigManager
     */
    public void removeNotificationListener(NotificationListener listner) throws ListenerNotFoundException {
        NotificationListener registeredListener = myListener.getListener();
        if (registeredListener.equals(listner))
            myListener = null;
    }
    /**
     * Returns information about management notifications sent by this object
     * @return information about management notifications sent by this object
     */
    public MBeanNotificationInfo[] getNotificationInfo() {
        String[] notifsType = new String[2];
        notifsType[0] = new String(RECONFIG_TYPE);
        notifsType[1] = new String(SAVE_RECONFIG_TYPE);

        MBeanNotificationInfo[] myNotifInfos = new MBeanNotificationInfo[2];
        MBeanNotificationInfo myNotifInfo = new MBeanNotificationInfo(notifsType, RECONFIG_NOTIF_CLASS, "Notify service reconfiguration events");
        myNotifInfos[0] = myNotifInfo;

        myNotifInfo = new MBeanNotificationInfo(notifsType, SAVE_RECONFIG_NOTIF_CLASS, "Notify save reconfiguretion events");
        myNotifInfos[1] = myNotifInfo;

        return myNotifInfos;
    }

    /**
     * Returns the listener reference (the ReconfigManager)
     * @return the ReconfigManager reference
     */
    public NotificationListener getListener() {
        if (myListener != null)
            return myListener.getListener();
        else
            return null;
    }
    /**
     * Returns the listner's filter
     * @return the filter object
     */
    public NotificationFilter getFilter() {
        if (myListener != null)
            return myListener.getFilter();
        else
            return null;
    }
    /**
     * Returns the listner's handback
     * @return the handback object
     */
    public java.lang.Object getHandback() {
        if (myListener != null)
            return myListener.getHandback();
        else
            return null;
    }

    /**
     * Send a <i>save configuration</i> notification to the registerd listener. If no listener,
     * then log an error message.
     * @param sequenceNumber notification attribute
     * @param resourceName the name of a reconfigurable resource or of a JOnAS service
     */
    public void sendSaveNotification(long sequenceNumber, String resourceName) {
        // create notification
        Notification saveNotif = new Notification(SAVE_RECONFIG_TYPE, this, sequenceNumber, resourceName);
        if (slogger.isLoggable(BasicLevel.DEBUG)) {
            slogger.log(BasicLevel.DEBUG, saveNotif.getType() + " notification object created");
        }

        // get listener and emit notification to it
        NotificationListener listenerMBean = getListener();
        Object handback = getHandback();
        if (listenerMBean != null) {
            listenerMBean.handleNotification(saveNotif, handback);
        } else {
            if (slogger.isLoggable(BasicLevel.DEBUG)) {
                slogger.log(BasicLevel.ERROR, "MBean can't send management notification as no listener registered !!");
            }
        }
    }

    /**
     * Send a <i>reconfiguration</i> notification to the registerd listener. If no listener,
     * then log an error message.
     * @param sequenceNumber notification attribute
     * @param resourceName the name of a reconfigurable resource or of a JOnAS service
     * @param userData data containing the name and the value of the reconfigured property(or properties)
     */
    public void sendReconfigNotification(long sequenceNumber, String resourceName, Object userData) {
        // create notification and set the userData
        Notification configNotif =  new Notification(RECONFIG_TYPE, this, sequenceNumber, resourceName);
        configNotif.setUserData(userData);
        if (slogger.isLoggable(BasicLevel.DEBUG)) {
            slogger.log(BasicLevel.DEBUG, configNotif.getType() + " notification object created");
        }

        // get listener and emit notification to it
        NotificationListener listenerMBean = getListener();
        Object handback = getHandback();
        if (listenerMBean != null) {
            listenerMBean.handleNotification(configNotif, handback);
        } else {
            if (slogger.isLoggable(BasicLevel.DEBUG)) {
                slogger.log(BasicLevel.ERROR, "MBean can't send management notification as no listener registered !!");
            }
        }
    }
}
