package wbModule;
import java.net.*;
import utility.*;
public class WbAgent implements Runnable
{
	public static AgentIdentity id = null;
	public static String serverIP = null;
	public static int portNo =0;
	public WbClientHandler cliHandler = null;

	Thread t ;
	public WbAgent()
	{
		t = new Thread(this);

		boolean success = false;
		if(id != null)
		{
			try
			{
				Socket srvConn = new Socket(serverIP, portNo);
        			t = new Thread(this);

				synchronized (srvConn.getInputStream())
				{

					System.out.println("Starting White board Agent :");
					cliHandler = new WbClientHandler(srvConn.getInputStream(),srvConn.getOutputStream());
					System.out.println("Got socket to whiteBoard server :");

					Request req = new Request (id,"Add");
					ClientHeader toBeSent = new ClientHeader (req);
					cliHandler.sendRequest(toBeSent);

					Response res = cliHandler.readResponse();
        				//System.out.println("Got Response" );
        				if (res.getResponseType().compareTo("AddAccepted") == 0)
					{
          					AgentIdentity aid = (AgentIdentity)res.getObject();
                    				 aid.setLoginName(id.getLoginName());
						cliHandler.setAgentId(aid);
						//System.out.println("Got identity from mediator, id = "+ aid.getId());
          					cliHandler.g.showGui();
						success = true;
					}
 		       			if (res.getResponseType().compareTo("AddRejected") == 0)
					{
          					cliHandler.removeConnection();
          					success = false;
        				}
      				}
			}
      			catch (Exception e)
			{
        			success = false;
      				e.printStackTrace();
			}
		}
		if(!success)
		{
			System.out.println("couldn't esatblish connection ");
			cliHandler.removeConnection();
		}
		else
			t.start();
	}


	public  void logOff()
	{
		if (cliHandler != null && id != null)
		{
			System.out.println("Sending logOff req to White Board Server :");
			cliHandler.logOff(id);
			cliHandler.g.dispose();
		}
		else
			System.out.println("cudn't send  logOff req white board server :");
	}



	public AgentIdentity getIdentity()
  	{
		return id;
	}
	public void run()
	{
		try
		{
			cliHandler.t.join();

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

	}

	public static void main(String args[])
	{
		WbAgent ca = new WbAgent();
		ca.id.setLoginName("kapil ");
		try
		{
			ca.t.join();

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

}
