package wbModule;
import java.util.*;
import java.net.*;
import java.io.*;
import utility.*;
public class WbServer implements Runnable
{
	WbServerHandler srvHandler = new WbServerHandler();
	ServerSocket socket = null;
	int port = 9000;
	Thread t = null;
  	public WbServer(int port)
	{
		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("White Board  server running on port " + port);
		while (true)
		{
			try
			{
        			Socket clientConn = socket.accept();
        			AgentIdentity id = newClientAgent();
        			srvHandler.addConnection(id, clientConn.getInputStream(), clientConn.getOutputStream());
        			System.out.println("Got new connection...");
        			//Response res  = new Response(id,"Identity");
				//ServerHeader toBeSent = new ServerHeader(res);
     				//srvHandler.sendResponse(toBeSent, id.getId());
      			}
      			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 WbServer(9000);
		while(true)
		{}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
