package nxm.sys.intr;

import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.KeyObject;

/**
  Handles the creation of a Layer object.

  @author Jeff Schoen

*/
public class Layer extends Intrinsic {

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

  public int open() {
    nxm.sys.lib.Table  table = null;
    nxm.sys.libg.Layer layer = null;

    // Get parameters
    String name   = MA.getCS("NAME");
    String label  = MA.getU("LABEL");
    String plotid = MA.getU("PLOT");
    table = MA.getTable("TABLE");
    if (name.indexOf(".")<0) name = "nxm.sys.libg.Layer"+name;

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

    if (table!=null) KeyObject.setKeys(layer,table,args,0);

    MR.put(label,layer,args);

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

    /**
    Create a default LAYER name for LAYERS 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 layer naming to ensure a unique name of the form "LAYER_#"

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

}
