package graphics.raytracer;

import rmi.rmiSynth.Host;
import rmi.rmiSynth.HostManager;
import rmi.rmiSynth.HostManagerInterface;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 *   The DoImageClientManager uses the <code>HostManager</code>
 * to find image servers.
 */
public class DoImageClientManager {


  public DoImageClientManager() {
  }

  /**
   *
   */
  public DoImageInterface getNextProxy() {
    //locate the server class on remote machine
    Registry r = getNextHostAndLocateRegistry();
    return lookupImageServer(r);

  }

  private DoImageInterface lookupImageServer(Registry r) {
    System.out.println("Registry:\n\t" + r + "\n\t Looking up DoImageInterface");
    Object o = null;
    try {
      o = r.lookup(
          "DoImageServer");
    } catch (RemoteException e) {
      System.out.println("ERROR:DoImageInterface RemoteException on lookup");
      System.exit(0);
    } catch (NotBoundException e) {
      System.out.println("ERROR:DoImageInterface NotBoundException on lookup");
      System.exit(0);
    }
    return (DoImageInterface) o;
  }

  private Registry getNextHostAndLocateRegistry() {
    Host h = null;
    try {
      HostManagerInterface hm = HostManager.getProxy();
      h = hm.getNextHost();
      System.out.println("Got a host:" + h);
    } catch (RemoteException e) {
      System.out.println("ERROR:DoImageInterface;HostMaster.getNextHost");
      System.exit(0);
    }
    Registry r = null;
    try {
      //r = LocateRegistry.getRegistry(h.toString());
      String hs = h.toString();
      String ips = hs.substring(hs.indexOf('/') + 1);
      System.out.println("ipstring for registry is:" + h.getIP());
      r = LocateRegistry.getRegistry(h.getIP()); //CHANGE ME!
    } catch (RemoteException e) {
      System.out.println("ERROR:DoImageInterface;HostMaster.getRegistry");
    }
    return r;
  }

}