package chat;

import java.util.Vector;

/**
 * \class TextChatroom
 * Provides an implementation of the chatroom model.
 */
public class TextChatroom implements Chatroom {
	private Vector<Chatter> chatters = new Vector<Chatter>();
	private String topic;
	
	/**
	 * constructor
	 * \param the name of the topic
	 */
	public TextChatroom(String topic) {
		super();
		this.topic = topic;
	}

	public void join(Chatter c) {
		if (!chatters.contains(c)) {
			chatters.add(c);
			System.out.println("(Message from Chatroom : " + topic + ") " + c.getPseudo() + " has join the room.");
			for (int i = 0 ; i < chatters.size() ; i++) {
				chatters.elementAt(i).joinNotification(c);
			}
		}
	}

	public void post(String msg, Chatter c) {
		if (chatters.contains(c)) {
			for (int i = 0 ; i < chatters.size() ; i++) {
				chatters.elementAt(i).receiveAMessage(msg, c);
			}
		} else {
			System.out.println("ERROR : message \"" + msg + "\" could not be sent. Sender " + c.getPseudo() + " not in the chatroom");
		}
	}
	
	public void quit(Chatter c) {
		// we check that c is in the chatroom
		if (chatters.contains(c)) {
			chatters.removeElement(c);
			System.out.println("(Message from Chatroom : " + topic + ") " + c.getPseudo() + " has quit the room.");
		}
		for (int i = 0 ; i < chatters.size() ; i++) {
			chatters.elementAt(i).quitNotification(c);
		}
	}

	public String getTopic() {
		return topic;
	}
}
