package nxm.sys.intr;

import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.StringUtil;

/** Defaults Primitive: used to show command entry in dictionary. Prior to NeXtMidas 2.3.0 this
    class was named Default; the name was changed so the command would match X-Midas usage.

    @author  Sid Moore
    @since   NeXtMidas 2.3.0 - Previously named Default (no 's').
*/
public class Defaults extends Intrinsic {

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

  @Override
  public int open() {
    String name   = MA.getS("NAME");
    String option = MA.getS("OPTION");
    String type   = MA.getS("TYPE");
    int    isemi  = name.indexOf(';');

    if (isemi > 0) {
      // Name given using <name>;<opt> syndax (Bug 1129)
      String opt = name.substring(isemi+1);
      if ((option.length() > 0) && !option.equals(opt)) {
        M.warning("Conflicting specification of option name OPTION="+option+" and ;"+opt+" both used, using "+opt+".");
      }
      name   = name.substring(0,isemi);
      option = opt;
    }

    boolean matchFound = false; // Keep track of whether match was found - Since 3.7.0 for Bug 2996

    // loop through all the entries in the dictionary
    for (int i = 0; i < M.dictionary.getSize(); i++) {
      nxm.sys.lib.Table entry = M.dictionary.getEntry(i);
      String cmdName = entry.getS("NAME");
      String command = entry.getS("CMD");
      String cmdOpt  = entry.getS("OPT");
      String cmdSup  = entry.getS("SUP");
      String nargs   = entry.getS("NARGS");
      String nameOpt = cmdName+";"+cmdOpt;

      /* no name entered or name matches */
      if (name.length()<=0 || nameOpt.startsWith(name)) {
        /* type not entered or type matches */
        if (type.length()<=0 || type.lastIndexOf(cmdSup) > -1) {
          /* option not entered or matches */
          if (option.length()<=0 || cmdOpt.equals(option)) {
            String value = StringUtil.padRight(command+";"+cmdOpt+" ", 20)
                         + StringUtil.padRight(cmdSup+","+nargs+" ", 8)+",";
            int    index = 1;
            String def   = null;

            while ((def = entry.getS("DEF"+index)) != null) {
              value += def+",";
              index++;
            }
            M.info(value);
            matchFound = true;  // match was found - Since 3.7.0 for Bug 2996
          }
        }
      }
    }
    if (!matchFound) { // WARN if match not found - Since 3.7.0 for Bug 2996
      M.warning ("No command dictionary entry matching NAME="+name+", OPTION="+option+", TYPE="+type);
    }
    return FINISH;
  }
}
