package nxm.sys.intr;

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

/**
  Handles the removal of results parameters.

  @author Jeff Schoen
*/
public class Remove extends Intrinsic {

  /** protected results table containing results which cannot be modified */
  public static final nxm.sys.lib.Table Protected_Results_Table
          = new nxm.sys.lib.Table ("{1=OPT,2=REG,3=AUX,4=ENV,5=RAM}"); // <-- TODO: Why is this public?

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

  public int process() {

    // Get parameters
    boolean force  = MA.getState("/FORCE");
    int removeOption = (force)? nxm.sys.lib.Table.FORCE : 0;
    verbose = MA.getState("/VERBOSE",false);
    nxm.sys.lib.Table rt = MR;
    if (MA.getState("/PARENT")) rt = MR.getPrevious();
    if (MA.getState("/GLOBAL")) rt = MR.getRoot();

    // remove listed values
    for (int i=1; i<=MA.numberOf(); i++) {
      String label = MA.getU(i);
      if (StringUtil.isWildcardString(label)) {
        for (nxm.sys.lib.Table.Iterator ti=rt.iterator(); ti.getNext(); ) {
          String key = ti.key;
          if (StringUtil.isWildcardMatch(label,key)){
            if (isProtected(key)) {
              if (verbose) M.println(key+" is protected ");  // since 3.7.1 using M.println instead of M.terminal.writeln to allow logging - NXM-1813
            }
            else {
              if (verbose) M.println("removing "+key);
              rt.remove(key);
            }
          }
        }
      }
      else {
        if (isProtected(label)) {
          if (verbose) M.println(label+" is protected ");
        }
        else {
          if (verbose) M.println("removing "+label);
          rt.remove(label, removeOption); // fix for Bug 1870 to honor /FORCE flag
        }
      }
    }
    return FINISH;
  }

  private static boolean isProtected (String label) {
    boolean isProtected = false;
    nxm.sys.lib.Table tab = Protected_Results_Table;
    for (nxm.sys.lib.Table.Iterator ti=tab.iterator(); ti.getNext(); ) {
      String protectedLabel = ti.value.toString();
      if (protectedLabel.equals(label)) {
        isProtected = true;
        break;
      }
    }
    return isProtected;
  }
}
