package chat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * A chat server: every line one client sends goes to every connected client.
 * The list of clients is shared by all the handler threads, so every method
 * that uses it is synchronized.
 */
public class ChatServer {

	public static final int PORT = 5001;

	private List<ChatHandler> clients_;

	public ChatServer () {
		clients_ = new ArrayList<ChatHandler>();
	}

	public synchronized void addClient ( ChatHandler client ) {
		clients_.add(client);
	}

	public synchronized void removeClient ( ChatHandler client ) {
		clients_.remove(client);
	}

	/**
	 * Sends message to every connected client.
	 */
	public synchronized void broadcast ( String message ) {
		for ( ChatHandler client : clients_ ) {
			client.send(message);
		}
	}

	public synchronized int getClientCount () {
		return clients_.size();
	}

	public static void main ( String[] args ) throws IOException {
		ChatServer chat = new ChatServer();
		ServerSocket server = new ServerSocket(PORT);
		System.out.println("chat server listening on port " + PORT);

		int count = 0;
		for ( ;; ) {
			Socket socket = server.accept();
			count++;
			try {
				Thread thread =
				    new Thread(new ChatHandler(socket,chat),"client-" + count);
				thread.start();
			} catch ( IOException e ) {
				System.out
				    .println("couldn't set up client-" + count + ": " + e.getMessage());
				socket.close();
			}
		}
	}

}
