/*
 *  Team 1
 *  CS575: Software Design
 *  Project Phase II
 *  Implicit Invocation style
 *  KWICBroacaster.java
 */

import java.util.Vector;
import java.util.Iterator;

/**
 *  <p>KWICBroadcaster class for the Imlicit Invocation KWIC system.
 *
 *  <p>This class simply contains a list of KWICListeners and when a message is posted 
 *  to the broadcaster, it will send it to every listener on its list.  
 *  </p>
 *
 *  <p>The KWICListeners must be registered by a third party class by calling the
 *  addListener method; the broadcaster cannot register them on its own.
 *  </p>
 *
 *  <p>First, the constructor of the class must be called.  After that, the class will 
 *  simply wait for messages to come in to its eventBroadcast() method.  These events
 *  will then be reported to all the listeners on the list.  
 *  </p>
 *
 *  @author Diana Tetelman
 */

public class KWICBroadcaster
{
    /**
     * keeps track of subscribed listeners
     */
    private Vector listeners;
    
    /**
     * keeps track of the last event broadcasted
     */
     private KWICEvent lastEvent;
    
    public KWICBroadcaster()
    {
        listeners = new Vector();
        lastEvent = null;
    }
    
    /**
     * Returns the last event received and broadcasted
     *@return   KWICEvent   last event received
     */
    public KWICEvent getLastEvent()
    {
        return lastEvent;
    }
 
    /**
     * Method that outside classes call to post message to be broadcasted to listeners.
     * @param    event  KWICEvent that is to be broadcasted
     */
     public synchronized void eventBroadcast(KWICEvent event)
    {
        lastEvent = event;
      
        Iterator i = listeners.iterator();
        while(i.hasNext())
	{
            ((KWICListener)(i.next())).eventArrived(event);
	}
    } 
     
    /**
     * Registers the listener, by adding the given listener to the list of subscribed listeners.
     * @param   listener    KWICListener that wants to receive message from this broadcaster.
     */
    public void addListener(KWICListener listener)
    {
        listeners.add(listener);
    }    
}
