package nbModule;
import java.net.*;
import java.io.*;
import utility.*;
public class NbDataAgent implements Runnable
{
	public static AgentIdentity id = null;
	public static String serverIP = null;
	public static int portNo =0;
	public NbDataClientHandler cliHandler = null;
	//public Strin
	Thread t ;
	public NbDataAgent()
	{
		t = new Thread(this);
		Socket srvConn = null;
		boolean success = false;
		try
		{
			System.out.println("connecting to "+serverIP+" "+ portNo);
			 srvConn = new Socket(serverIP, portNo);
        		t = new Thread(this);
			OutputStream out = srvConn.getOutputStream();
			synchronized (out)
			{
				Request req = new Request (id,"Add");
				ClientHeader toBeSent = new ClientHeader (req);
				ObjectOutputStream objOut = null;
				objOut = new ObjectOutputStream(out);
				objOut.writeObject(toBeSent);
				objOut.flush();
				//objOut.close();
				success = true;
				System.out.println("sent identity to Nb data Server");

			}

		}
      		catch (Exception e)
		{
        		success = false;
      			//System.out.println(serverIP);
			e.printStackTrace();
		}
		if(success)
		{
			try
			{
				cliHandler = new NbDataClientHandler(srvConn.getInputStream(),srvConn.getOutputStream());
				//System.out.println("starting nb data client handler ......");
				t.start();

			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			System.out.println("couldn't esatblish connection ");
			cliHandler.removeConnection();
		}


	}



	public AgentIdentity getIdentity()
  	{
		return id;
	}


	public void run()
	{
		try
		{
			cliHandler.t.join();

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

	}

}
