package rmi.rmiSynth;

// rmi.rmiSynth.HostManager

import gui.browser.HtmlSynthesizer;
import gui.html.Browser;

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
 * We need to provide a leasing mechanism that expires a host.
 * First start the host manager. Then start the computation servers.
 * Finally start the compute client
 */

public class HostManagerGui {

  HostManagerInterface hmi;

  HostManagerGui() {
    try {
      hmi = HostManager.getProxy();
    } catch (RemoteException e) {
      System.out.println(
          "Error:HostManagerGUI,Unable to get HostManager proxy is HostManager running?");
      exit();
    }
  }

  private void exit() {
    System.exit(0);
  }


  public void printHosts() {
    print(getHosts());
  }

  public void printHtml() {
    print(getHtml());
  }

  public String getHtml() {
    Host h[] = getHosts();
    HtmlSynthesizer hs = new HtmlSynthesizer();
    int xMax = h.length;
    int yMax = 2;
    String hostSheet [][] = new String[xMax][yMax];
    for (int x = 0; x < xMax; x++) {
      hostSheet[x][0] = hs.getCheckbox(h[x].getIP(), true)
          + "benchMark:"
          + h[x].getBenchMark();
      hostSheet[x][1] = h[x].toString();
    }
    String titles[][] = {
      {"on/off:BenchMark Run time", "Host Name/IP Address"}
    };

    return hs.getHtml(
        hs.getHead(
            hs.getTitle(
                "CentiJ Web Interface")) +
        hs.getBody(
            hs.getHomePage(1) +
            "CentiJ Web Interface" +
            hs.getTable(
                hs.getForm("processHostRequest", "get",
                           hs.getP(
                               hs.getSheet(titles)
                               + hs.getSheet(hostSheet))))
            + hs.getP(
                hs.getSubmit())
        )
    );
  }

  public void testHtmlDisplay() {
    Browser b = new Browser();
    HtmlSynthesizer hs = new HtmlSynthesizer();
    b.setString(getHtml());
  }

  public static void print(Object o[]) {
    for (int i = 0; i < o.length; i++) {
      print(o[i]);
    }
  }

  public Host[] getHosts() {
    try {
      System.out.println("Getting Hosts:");
      Host h[] = hmi.getHosts();
      print("there are:" + h.length + " hosts");
      return h;
    } catch (RemoteException e) {
      print("ERROR:HostManagerGUI, can't get hosts!");
      exit();
      return null;
    }
  }

  public static void print(Object o) {
    System.out.println(o);
  }

  public static void main(String args[]) {
    HostManagerGui hmg = new HostManagerGui();
    hmg.printHosts();
    hmg.printHtml();
    hmg.testHtmlDisplay();
  }


}