package rmi.rmiSynth;


import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;

/**
 *    The <code>HostManager</code> is invoked
 * remotely by unicast remote protocol. New workers that
 * enter into the grid must know the IP addBk.address of the HostManager
 */

public class Host implements Serializable {
  private InetAddress localAddress = null;

  private double benchMark = getBenchMark();


  // The timeOfUpdate is used by the HostManager to
  // determine if the lease has gui.run out on the host
  private long timeOfUpdate = 0;


  private void registerWithHostManager() {

    try {
      HostManagerInterface hmi = getProxy();
      System.out.println("I have the proxy to the hostmanagerinterface");
      registerWithHostManager(hmi);
      System.out.println("I have registerd with the host manager");
    } catch (RemoteException e) {
      System.out.println("could not add host, process dies!");
      System.exit(0);
    }

  }

  private void registerWithHostManager(HostManagerInterface hmi) throws RemoteException {
    benchMark = getBenchMark();
    hmi.add(this);
  }

  private HostManagerInterface getProxy() throws RemoteException {
    HostManagerInterface hmi =
        HostManager.getProxy();
    return hmi;
  }

  private void updateHostBenchMark() {
    benchMark = getBenchMark();
  }

  private void runBenchMark() {
    for (int i = 0; i < 10000; i++)
      Math.sin(i);
  }

  public double getBenchMark() {
    long startTime = System.currentTimeMillis();
    runBenchMark();
    long stopTime = System.currentTimeMillis();
    double seconds = (stopTime - startTime) / 1000.0;
    return seconds;
  }

  public String toString() {
    return localAddress.toString();
  }

  /**
   *   return the local addBk.address.
   */
  public String getIP() {
    return localAddress.getHostAddress();
  }

  public boolean equals(Host h) {
    System.out.println("h1=" + h.getIP());
    System.out.println("h2=" + getIP());
    return getIP().equals(h.getIP());
  }

  public Host() {
    try {
      System.out.println("new host instance...");
      localAddress = getAddress();
      System.out.println("addBk.address:" + localAddress);
    } catch (UnknownHostException e) {
      e.printStackTrace();
    }
  }

  public static void main(String args[]) {
    final Host h = new Host();
    System.out.println("host ip=" + h.getIP());

    Job j = new Job(1) {
      public void doCommand() {
        h.registerWithHostManager();
      }
    };

  }


  /**
   print(Host.getAddress()) to see the local IP.
   */
  public static InetAddress getAddress() throws UnknownHostException {
    InetAddress ia = InetAddress.getLocalHost();
    return ia;
  }

  public long getTimeOfUpdate() {
    return timeOfUpdate;
  }

  public void setTimeOfUpdate(long timeSinceUpdate) {
    this.timeOfUpdate = timeSinceUpdate;
  }
}