package chatModule;
import java.util.*;
import java.net.*;
import java.io.*;
import utility.*;
public class ChatServer implements Runnable
{
	ChatServerHandler srvHandler = new ChatServerHandler();
	ServerSocket socket = null;
	int port = 8000;
	Thread t = null;
  	public ChatServer(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("Chat 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...");
				//srvHandler.readRequest();
				/*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 ChatServer(8000);
		while(true)
		{}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
