/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.cuni.amis.utils.flag.jmx;

import cz.cuni.amis.utils.flag.Flag;
import cz.cuni.amis.utils.flag.FlagListener;
import cz.cuni.amis.utils.future.FlagFuture;
import javax.management.MBeanNotificationInfo;
import javax.management.NotificationBroadcasterSupport;

/**
 * Translates Flag events to JMX events. Adds a listener on the flag and resends 
 * the events to supplied broadcaster support.
 * @author Ik
 */
public class JMXFlagDecorator<T> {
    
    protected Flag<T> flag = null;
    
    protected NotificationBroadcasterSupport nbs = null;
    
    protected Object source;
    
    protected int eventCounter = 0;

    protected FlagListener<T> listener = new FlagListener<T>() {

        public void flagChanged(T changedValue) {
            nbs.sendNotification(new FlagChangeNotification(JMXFlagDecorator.this, changedValue));
        }
    };
    /**
     * 
     * @param flag Flag to be exposed through JMX.
     * @param source MBean or ObjectName of the object where the flag resides.
     * @param nbs NotificationBroadcasterSupport through which the events will be send.
     */
    public JMXFlagDecorator(Flag<T> flag, Object source, NotificationBroadcasterSupport nbs) {
        this.flag = flag;
        this.nbs = nbs;
        this.source = source;
        flag.addListener(listener);
    }
    
    /**
     * Stops listening for the flag events.
     */
    public void stop() {
        flag.removeListener(listener);
    }
    
    /**
     * 
     * @return Notification info about this events possibly raised by this flag.
     */
    public MBeanNotificationInfo getMBeanNotificationInfo() {
        return new MBeanNotificationInfo(new String[] {FlagChangeNotification.FLAG_CHANGE_EVENT_TYPE},
                FlagChangeNotification.class.getName(), "The flag has changed it's value.");
    }
}
