package nbModule;
import java.net.*;
import utility.*;
import javax.swing.*;
import java.io.File;
public class NbAgent implements Runnable
{
	public static AgentIdentity id = null;
	public static String serverIP = null;
	public static int portNo =0;
	public NbClientHandler cliHandler = null;
	JDesktopPane desktop = null;
	Thread t ;
	public NbAgent(JDesktopPane desktop)
	{
		this.desktop = desktop;
		t = new Thread(this);
		boolean success = false;
		if(id != null)
		{
			try
			{
				System.out.println("connecting to notice board server"+serverIP+" "+ portNo);
				Socket srvConn = new Socket(serverIP, portNo);
        			t = new Thread(this);

				synchronized (srvConn.getInputStream())
				{

					System.out.println("Starting Notice Board Agent  :");
   					cliHandler = new NbClientHandler(srvConn.getInputStream(),srvConn.getOutputStream(),desktop);
					System.out.println("Got socket to notice board 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("notice board login accepted");
          					cliHandler.g.showGui();
						success = true;

					}
        				else if (res.getResponseType().compareTo("AddRejected") == 0)
					{
          					System.out.println("login rejected");
						cliHandler.removeConnection();
          					success = false;
        				}
					else
						System.out.println("unknown res  " +res.getResponseType());
      				}
			}
      			catch (Exception e)
			{
        			success = false;
      				//System.out.println(serverIP);
				e.printStackTrace();
			}
		}
		if(!success)
		{
			System.out.println("couldn't esatblish connection ");
			cliHandler.removeConnection();
		}
		else
			t.start();
	}


	public AgentIdentity getIdentity()
  	{
		return id;
	}



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



	public boolean sendNotice(File file,String dateRemoval,String noticeName)
	{
		return cliHandler.sendNotice(file,dateRemoval,noticeName);
	}
	public void run()
	{
		try
		{
			cliHandler.t.join();

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

	}






}
