package net.lamot.java.jskype.general;

import java.util.HashSet;
import java.util.Iterator;

/**
 * Copyright (C) 2004  B. Lamot
 ***********************************************************
 *
 * 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 (at your option) 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.
 *
 ************************************************************
 *
 * A basic implementation all Messengers need, the listener method are implemented.
 * The sendMessage method should be overridden.
 */
public abstract class AbstractMessenger {
	
	/**
	 * Placeholder for the listeners that want to be notified on a received message.
	 */	
	private HashSet listeners = new HashSet(5);
	
	/**
	 * This method adds a listener, which will be triggered when a message is received.
	 * @param listener the listener which has to be added.
	 */
	public void addListener(MessageListenerInterface listener){
		listeners.add(listener);
	}
	
	/**
	 * Removes a previously added listener.
	 * @param listener the listener that needs to be removed.
	 */
	public final void removeListener(MessageListenerInterface listener) {
		listeners.remove(listener);
	}
		
	/**
	 * To be called by the messengers that extend this class.
	 * This will fire all the listeners.
	 * @param message the message the listeners have to be fired with.
	 */
	protected final void onMessageReceived(final String message){
		if (!listeners.isEmpty()){
			Iterator it = listeners.iterator();
			Object listener = new Object();
			while (it.hasNext()) {
				listener = it.next();
				if (listener instanceof MessageListenerInterface) {
					((MessageListenerInterface) listener).onMessageReceived(message);
				}
			}
		}
		
	}
	
	/**
	 * Messengers should override this method with their sendMessage implementation, dependant on the platform.
	 * @param message the message to send.
	 * @return false if message could not be send.
	 */
	abstract public boolean sendMessage(String message);
	
	/**
	 * Used to initialize the platform specific initialisation.
	 * @return false if initialisation went wrong.
	 */
	abstract public boolean initialize();
	
	/**
	 * Terminate this messenger and let it clean-up it's trash (jni trash or sockets and stuff).
	 *
	 */
	abstract public void destroy();
	
}
