package nxm.sys.intr;

import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.Midas;
import nxm.sys.lib.Results;
import nxm.sys.lib.Shell;

/** Run a NeXtMidas command stored in a results string. This NeXtMidas intrinsic
    accepts the following flags to change the lexical scope (i.e. the results set)
    to use when running the command.
    <table style="margin-left:auto;margin-right:auto;" border="1">
      <caption style="visibility:hidden">""</caption>
      <tr>
        <td style="text-align:center;"><b>Flag</b></td>
        <td style="text-align:left"><b>Lexical Scope</b></td>
      </tr>
      <tr>
        <td style="text-align:center;">&nbsp;<code>/GLOBAL</code>&nbsp;</td>
        <td style="text-align:left">Uses the global results set
                         (see {@link nxm.sys.lib.Results#getRoot()}).</td>
      </tr>
      <tr>
        <td style="text-align:center;">&nbsp;<code>/PARENT</code>&nbsp;</td>
        <td style="text-align:left">Uses next results set up
                         (see {@link nxm.sys.lib.Results#getPrevious()}), if
                         available; otherwise uses the global results set.</td>
      </tr>
      <tr>
        <td style="text-align:center;"><i>default</i></td>
        <td style="text-align:left">Uses the active results set.</td>
      </tr>
    </table>
    @author Jeff Schoen / J. Czechowski IV
*/
public class Run extends Intrinsic {

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

  public int process () {
    Midas midas=M;

    if (MA.getState("/GLOBAL")) {
      midas = M.cloneOf();
      midas.results = (nxm.sys.lib.Results)MR.getRoot();
    }
    else if (MA.getState("/PARENT")) {
      midas = M.cloneOf();
      midas.results = (nxm.sys.lib.Results)MR.getPrevious();
      if (midas.results == null) {
        midas.results = (nxm.sys.lib.Results)MR.getRoot();
      }
    }

    String cmd = MA.getRawArgs().trim();
    int lcmd = cmd.length();

    if (lcmd>=2 && cmd.charAt(0)=='"' && cmd.charAt(lcmd-1)=='"') {
      cmd = cmd.substring(1, lcmd-1);
    }
    else if (Results.validNameLength(cmd,0)==lcmd) {
      String rcmd = MR.getS (cmd.toUpperCase());
      if (rcmd!=null) cmd = rcmd;
    }

    if (cmd.length()==0) M.warning ("RUN command given no arguments");
    else Shell.runCommand(midas, cmd);

    return FINISH;
  }

}
