/**
 * JOnAS
 * Copyright (C) 2010 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 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: AuditComponentListener.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.audit.internal.logger;

import java.util.LinkedList;
import java.util.List;

import javax.management.ListenerNotFoundException;
import javax.management.MBeanServer;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.ObjectName;

import org.ow2.jonas.audit.internal.logger.api.IAuditComponentListener;
import org.ow2.jonas.audit.internal.logger.api.IAuditLogListener;
import org.ow2.util.auditreport.impl.jmx.ListeningChecker;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;


/**
 * Manage the connection with the audit component.
 * Receive notification from the audit component and
 * dispatch the event to the listeners.
 * @author Vincent Michaud
 */
public class AuditComponentListener implements IAuditComponentListener, NotificationListener {

    /**
     * Logger.
     */
    private Log logger = LogFactory.getLog(AuditComponentListener.class);

    /**
     * The JMX server.
     */
    private MBeanServer jmxServer = null;

    /**
     * JMX Name.
     */
    private ObjectName jmxName;

    /**
     * Number of invocations detected.
     */
    private int invocations = 0;

    /**
     * Listeners of the notification from audit component.
     */
    private List<IAuditLogListener> listeners = new LinkedList<IAuditLogListener>();

    /**
     * Constructor.
     * @param jmxServer the JMX Server
     */
    public AuditComponentListener(final MBeanServer jmxServer) {
        this.jmxServer = jmxServer;
    }


    /**
     * This method add a listener on a MBean if this MBean is present in the JMX server.
     * @param jmxName the objectname on which we needs to be registered
     * @throws AuditLogServiceException A communication problem occurred when talking to
     *                               the MBean server.
     */
    public final void register(final ObjectName jmxName) throws AuditLogServiceException {
        this.jmxName = jmxName;
        try {
            if (jmxServer.isRegistered(jmxName)) {
                this.unregister();
                ListeningChecker checker = new ListeningChecker(jmxName, this);
                checker.start();
                jmxServer.addNotificationListener(jmxName, this, null, null);
            } else {
                logger.warn("The MBean '" + jmxName + "' is not registered");
            }
        } catch (Exception ex) {
            throw new AuditLogServiceException(ex);
        }
    }

    /**
     * Unregister the JMX listener.
     * @return True if JMX listener was unregistred, false otherwise.
     * @throws AuditLogServiceException A communication problem occurred when
     *                               talking to the MBean server.
     */
    public final boolean unregister() throws AuditLogServiceException {
        if (jmxName == null) {
            return true;
        }
        try {
            if (jmxServer.isRegistered(jmxName)) {
                jmxServer.removeNotificationListener(jmxName, this);
            }
        } catch (ListenerNotFoundException e) {
            logger.debug("Listener not found when unregistering", e);
           return true;
        } catch (Exception e) {
            logger.error("Listener not found when unregistering", e);
            return false;
        }
        return true;
    }

    /**
     * Add a listener.
     * @param listener The listener
     */
    public void addLogListener(final IAuditLogListener listener) {
        listeners.add(listener);
    }

    /**
     * Remove a listener.
     * @param listener The listener
     */
    public void removeLogListener(final IAuditLogListener listener) {
        boolean ok = true;
        while (ok) {
            ok = listeners.remove(listener);
        }
    }

    /**
     * This method handle a JMX notification.
     * @param notification The notification.
     * @param handback The handback.
     */
    public void handleNotification(final Notification notification, final Object handback) {
        String report = notification.getMessage();
        String type = notification.getType();
        for (IAuditLogListener listener : this.listeners) {
            listener.onAuditReceived(type, report);
        }
        invocations++;
    }

    /**
     * @return number of invocations.
     */
    public final int getNbInvocations() {
        return invocations;
    }

}
