package nxm.sys.intr;

import nxm.sys.lib.BaseFile;
import nxm.sys.lib.Convert;
import nxm.sys.lib.DataFile;
import nxm.sys.lib.FileName;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.KeyObject;

/** Import an OS environment variable or non-Midas file into the NeXtMidas shell.

    @author  Jay Hallam
*/
public class Import extends Intrinsic {

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

  private boolean showWarnings = true;
  public int process() {
    showWarnings = MA.getState("/WARN",showWarnings);
    if (MA.getState("/F")) {
      importFile();
    } else {
      importEnv();
    }

    return (FINISH);
  }

  private void importEnv() {
//    String in = MA.getCS("IN");
//System.out.println("IN: getCS='"+in+"', getString()= '"+MA.getString("IN",null,0)+"'");
//jph
    String in = MA.getString("IN",null,0); // TBD - perhaps we want a getUCS in Args
    String out = MA.getU("OUT");
    String def = MA.getCS("DEF");

    if (in==null  || in.length()==0)  { M.error("Must give a variable name to import"); }
    if (out==null || out.length()==0) { out = in.toUpperCase(); }

    Object value = null;

    if (in.equalsIgnoreCase("all")) {
      value = nxm.sys.lib.Import.getEnvTable();
    } else {
//jph -- Fix for Bug 1822 -- Handle case when ANY env, not necessarily
//       the one you are trying to retrieve, contains a dot (.)
//      value = nxm.sys.lib.Import.getEnvTable().getS(in, null);
      value = nxm.sys.lib.Import.getEnv(in);
    }

    if (value != null) {
      MR.put(out,value);
    } else {
      if (!MR.containsKey(out) && !def.equals("")) {
        value = def;
        MR.put(out, value);
      }
      else if (showWarnings) M.warning("Could not find ENV variable '"+in+"'");
    }
  }

  private void importFile() {
    // find the file to import
    BaseFile bfi = MA.getBaseFile("IN");
    if (bfi.open()) M.info("Importing URL="+bfi.getURL());
    else M.error("Could not find URL="+bfi.getURL());
    if (bfi instanceof DataFile) {
      M.error("URL="+bfi.getURL()+" is already a Midas file");
    }
    FileName fileName = bfi.getFileName();
    String extension = fileName.getExt();
    if (extension.equals("tmp") || extension.equals("prm")) {
      M.error("Cannot import files with .tmp or .prm extensions - rename");
    }
   // bfi.close();  // moved to end of method per Bug 2174

    // form the import file name
    FileName fn = new FileName( bfi.getURL() );
    fn.setExt("tmp");
    String newname = MA.getCS("OUT");
    boolean rename = newname.length()>0;
    if (rename) fn.setRoot(newname);

    // check if the output file already exists
    DataFile dfi = new DataFile (this,fn);
    if (dfi.find(-1)) {
      dfi.erase(false);
      M.info("Erased Midas file URL="+dfi.getURL());
    }

    // form the detached header file
    DataFile dfo = new DataFile (this,fn);
    dfo.setFormat("SB");
    //dfo.open(dfo.OUTPUT);  // changed to line below per BUG 2174
    dfo.open(BaseFile.OUTPUT|BaseFile.HEADERONLY);
    if (rename) dfo.setDetached(1);
    else dfo.setDetached(extension);
    dfo.setDataStart(0.0);
    dfo.setDataSize(bfi.getSize());
    //dfo.seek(bfi.getSize());  // JWB: commented out per BUG 2174 since it does not seem to do anything
    double  size        = -1;
    boolean dataSizeSet = false;
    for (int n=3; n<=MA.numberOf(); n++) {
      String key = MA.getKey(n);
      Object value = MA.getO(key);
      if (key.equals("DATASIZE")) dataSizeSet = true;
      if (key.equals("SIZE"))     size = Convert.o2d(value);
      else                        KeyObject.setKey (dfo,key,value,M);
    }

    // SIZE (# elements) takes precedences over DATASIZE (# bytes)
    if (size == -1) {   // size not set by the user
      if (dataSizeSet)  size = (dfo.getDataSize())/dfo.getBPE();   // dataSize is set, so adjust off that
      else              size = (bfi.getSize() - dfo.getDataStart()) / dfo.getBPE();
    }
    dfo.setSize(size);

    dfo.update();
    dfo.close();
    M.info("Created Midas header file URL="+dfo.getURL());

    // rename the detached data file
    if (rename) {
      fn.setExt("det");
      bfi.rename( fn.getFullName() );
      M.info("Renamed Import file to "+fn.getFullName());
    }
    bfi.close();
  }
}
