package server;

import java.io.IOException;
import java.util.HashMap;

import chat.Chatroom;
import chat.ChatroomExistsException;
import chat.TextTopicsManager;

public class TCPTopicsManager extends TextTopicsManager {
	private static int nextPort = 16000;
	
	private HashMap<String, ServerChatroom> tcpChatrooms = new HashMap<String, ServerChatroom>();  
	
	public void createTopic(String topic) {
		try {
			super.createTopic(topic);
			Chatroom chatroom = super.joinTopic(topic);
			ServerChatroom serverChatroom = new ServerChatroom(chatroom);
			tcpChatrooms.put(topic, serverChatroom);
			boolean started = true;
			//System.out.println("before while");
			do {
				try {
					serverChatroom.startServer(nextPort);
					started = true;
				} catch (IOException e) {
					started = false;
					e.printStackTrace();
				}
				nextPort++;
				//System.out.println("in while");
			} while(!started);
			//System.out.println("off while");
		} catch (ChatroomExistsException e) {
			//System.out.println(e);
			e.printStackTrace();
		}
	}
	
	public int getTopicPort(String topic) {
		return tcpChatrooms.get(topic).getPort();		
	}
}
