package nxm.sys.intr;

import nxm.sys.lib.Command;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.Macro;
import nxm.sys.lib.Time;

/** Handles the manipulation of Registry entries.

    @author Jeff Schoen
*/
public class Registry extends Intrinsic {
  String func,p1,p2;
  boolean all;

  /** default constructor */
  public Registry () {}

  public int process() {
    // Get parameters
    func  = MA.getU("FUNC");
    p1    = MA.getU("P1");
    p2    = MA.getU("P2");
    all   = MA.getState("/ALL");

    if (func.equals("SHOW")) {
      if (p1.length() == 0) {
        nxm.sys.intr.Results.listSingleResult (M,M.results,"REG",0,all);
      } else {
        Object cmd = M.results.get("REG."+p1);
        if (cmd == null) {
          M.warning("REGISTRY: "+p1+" not found.");
        } else if (cmd instanceof Macro) {
          nxm.sys.intr.Results.listMultipleResult (M, ((Macro)cmd).getRegistry(),"*",0,true);
        } else {
          nxm.sys.intr.Results.listSingleResult (M,M.results,"REG."+p1,0,all);
        }
      }
    }
    else if (func.equals("SET")) {
      M.warning (func+" function: not yet CODED");
    }
    else if (func.equals("GET")) {
      M.warning (func+" function: not yet CODED");
    }
    else if (func.equals("START")  || func.equals("STOP")
          || func.equals("RUN")    || func.equals("PAUSE")
          || func.equals("FINISH") || func.equals("ABORT")) {
      Command cmd = M.registry.getCommand(p1,0);
      if (cmd==null) M.error("Command "+p1+" not found in registry");
      cmd.setState(func);
      double timeout = MA.getD("/TIMEOUT",MA.getD("P2",5.0));
      if (func.equals("FINISH") || func.equals("ABORT")) {
        while (timeout>=0 && cmd.state!=DONE) { Time.sleep(0.1); timeout -= 0.1; }
      }
      if (func.equals("START") || func.equals("RUN")) {
        while (timeout>=0 && cmd.state!=PROCESS) { Time.sleep(0.1); timeout -= 0.1; }
      }
      if (timeout<0) M.warning("Command "+p1+" to "+func+" timed out");
    }
    else if (func.equals("WAIT")) {
      Command cmd = M.registry.getCommand(p1,0);
      if (cmd==null) M.error("Command "+p1+" not found in registry");
      double timeout = MA.getD("/TIMEOUT",MA.getD("P2",5.0));
      while (timeout>=0 && (cmd.state==INIT||cmd.state==OPEN)) { Time.sleep(0.1); timeout -= 0.1; }
      if (timeout<0) M.warning("Command "+p1+" to "+func+" timed out");
    }
    else if (func.startsWith("COPY")) {
      Object entry = M.registry.get(p1);
      if (entry == null) M.error ("Object not in registry");
      else M.registry.put(p2,entry);
    }
    else M.warning ("Unsupported function: "+func);

    return FINISH;
  }
}
