package kr.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import kr.AudioChannelModel;
import kr.AudioModel;
import kr.AudioModel.MessageType;

public class ListenerManager implements Listener
{
	private static ListenerManager inst = new ListenerManager();
	
	private HashMap<Object, List<Listener>> listeners = new HashMap<Object, List<Listener>>();
	
	public static ListenerManager inst()
	{
		return inst;
	}
	
	public void registerListener(Object source, Listener listener)
	{
		List<Listener> l = listeners.get(source);
		if(l == null)
		{
			listeners.put(source, l = new ArrayList<Listener>());
		}
		
		if(!l.contains(listener))
			l.add(listener);
	}
	
	public void notify(Object source, Object messageType, Object... values)
	{
		List<Listener> lList = listeners.get(source);
		
		if(lList == null) return;
		
		for(Listener l : lList)
		{
			l.notify(source, messageType, values);
		}
	}

	public void unregisterListener(Object source, Listener listener) {
		List<Listener> l = listeners.get(source);
		if(l != null)
		{
			l.remove(listener);
		}
	}

	/**
	 * Uses SwingUtilities.invokeLater() to use the awt thread to notify the listeners
	 */
	public void notifyGui(final Object source, final Object messageType, final Object... values)
	{
		new Thread() { public void run() {ListenerManager.this.notify(source, messageType, values);}}.start();
	}

}

