package nbModule;
import java.util.*;
import java.net.*;
import java.io.*;
import utility.*;

public class NbServer implements Runnable
{
	NbServerHandler srvHandler = new NbServerHandler();
	//NbDataServerHandler dataSrvHandler = new NbDataServerHandler();
	ServerSocket socket = null;
	int port = 6050;
	Thread t = null;
  	public NbServer(int port)
	{
		//srvHandler.addDataServer(dataSrvHandler);
		this.port = port;
  		t=new Thread(this);
		t.start();
	}
	public void run()
	{
		try
		{
      			socket = new ServerSocket(port);
    		}
    		catch (IOException e)
		{
      			System.out.println("Failed to bind to port " + port);
      			return;
    		}
		System.out.println("noticeBoard server running on port " + port);
		while (true)
		{
			try
			{
        			Socket clientConn = socket.accept();
				AgentIdentity id = newClientAgent();
        			srvHandler.addConnection(id, clientConn.getInputStream(), clientConn.getOutputStream());
        			//dataSrvHandler.addConnection(id, clientConn.getInputStream(), clientConn.getOutputStream());
				System.out.println("Got new connection...");

      			}
      			catch (Exception e)
			{
				e.printStackTrace();
			}
    		}
	}

  	public AgentIdentity newClientAgent()
	{
    		int id = srvHandler.nextConnectionId();
    		AgentIdentity i = new AgentIdentity(id);
    		return i;
  	}

  	public boolean remove(AgentIdentity id)
	{
    		int aId = id.getId();
    		boolean success = srvHandler.removeConnection(aId);
    		return success;
 	}
	public static void main(String args[])
	{
		try
		{
		new NbServer(6050);
		while(true)
		{}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
