package nxm.sys.intr;

import java.awt.HeadlessException;

import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.KeyObject;
import nxm.sys.lib.Shell;
import nxm.sys.libg.Theme;

/**
  Handles the creation of a Feature object.

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

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

  public int process() {
    nxm.sys.lib.Table   table   = null;
    nxm.sys.libg.Feature feature = null;

    // Get parameters
    String name  = MA.getS("NAME");
    String label = MA.getU("LABEL");
    String plotid = MA.getU("PLOT");
    table = MA.getTable("TABLE");

    if (name.indexOf(".")<0) {
      name = "nxm.sys.libg.Feature"+name;
    }

    if (Shell.isHeadless()) { // Since NeXtMidas 3.5.0 Throw headless exception if headless/bad display BUG 2817
      boolean headlessSwitch = false;
      //if (mh instanceof Command) {
      //  headlessSwitch = ((Command)mh).args.getState("/HEADLESS");
      //}
      //headlessSwitch = Args.getState("/HEADLESS");              TODO: check the user switch.
      boolean userSpecHeadless = headlessSwitch || Theme.getOption(Theme.HEADLESS);
      if (!userSpecHeadless && Theme.getHeadlessInitStatus() != 0) {
        String warningText = "/HEADLESS not set on a headless system. Error Code: "+Theme.getHeadlessInitStatus();
        HeadlessException headlessEx = new HeadlessException(warningText);
        throw headlessEx;
      }
    }

    try {
      feature = (nxm.sys.libg.Feature)Class.forName(name).getConstructor().newInstance(); // updated in 3.9.0 to use constructor
      feature.setRef(M);
    }
    catch (Exception e) { M.error(e); }

    KeyObject.setKeys (feature,table,args,0);

    MR.put(label, feature, args);

    if (plotid!=null && plotid.length()>0) {
      nxm.sys.prim.plot plot = (nxm.sys.prim.plot)M.registry.get(plotid);
      if (plot!=null) {
        // if FEATURE name was not specified, create a default name
        if (feature.getName() == null){
          feature.setName(getDefaultFeatureName(plot, label));
        }
        plot.MP.addFeature(feature);
      }
    }
    return FINISH;
  }

  /**
    Create a default FEATURE name for FEATURES that are missing a NAME.

    1) Use the LABEL as the default name, if it is available and not in use already as a name
    2) Use plot's auto feature naming to ensure a unique name of the form "FEATURE_#"

    @param plot associated plot with this FEATURE
    @param label label given to the FEATURE (empty string if not available)
    @return "default" feature named as described above
    @since 3.5.1
   */
  private String getDefaultFeatureName(nxm.sys.prim.plot plot, String label){
    String featureName = "" ;
    if (label.trim().length() > 0) {                       // 1. use label as feature NAME
      boolean nameInUse = (plot.MP.features.findKey(label.trim()) >=0);
      if (!nameInUse) {
        featureName = label.trim();
      }
    }
    if (featureName.length() == 0) {
      featureName = plot.getAutoFeatureName("FEATURE_"); // 2. use plot's auto feature naming to ensure uniqueness
      M.warning("No unique name given for FEATURE, using " + featureName);
    }
    return featureName;
  }

}