package nxm.sys.libxm;

import nxm.sys.inc.DataTypes;
import nxm.sys.inc.InternalUseOnly;
import nxm.sys.inc.Keyable;
import nxm.sys.lib.Data;
import nxm.sys.lib.MidasException;
import nxm.sys.lib.Parser;

/** Maps the X-Midas results table.<br>
    <span style="color:red">Do NOT use this class directly, this class
    is for use by the SYS option tree ONLY and is subject to change without notice! </span>

    @author prp
 */
@InternalUseOnly
public class XmResultTable extends Object implements Keyable {

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

  @Override
  public Object getKey(String key) {
    return XMidas.rfind(key);
  }

  @Override
  public Object setKey(String key, Object value) {
    //System.out.println("XmResultTable.setKey("+key+", "+value+")");
    char type = ' '; // Insert type (' ' = not set)
    int  len  = -1;  // Number of bytes inserted (-1 for failure).

    if (key.startsWith("\"") && key.endsWith("\"")) {
      key = key.substring(1, key.length()-1); // Remove quotes (used to access hidden results).
    }

         if (value instanceof String ) { type = (char)DataTypes.ASCII; }
    else if (value instanceof Data   ) { type = ' '; } // Data is handled later.
    else if (value instanceof Double ) { type = (char)DataTypes.DOUBLE; }
    else if (value instanceof Float  ) { type = (char)DataTypes.FLOAT; }
    else if (value instanceof Long   ) { type = (char)DataTypes.XLONG; }
    else if (value instanceof Integer) { type = (char)DataTypes.LONG; }
    else if (value instanceof Short  ) { type = (char)DataTypes.INT; }
    else if (value instanceof Byte   ) { type = (char)DataTypes.BYTE; }
    else                               { type = (char)DataTypes.ASCII; }

    if (value == null) {
      XMidas.del_result(key, 0);
      len = 0;

    } else if ((value instanceof Data) && (type == ' ')) {
      Data data = (Data)value;
      type = (char)data.getFormatType();
      if (type == DataTypes.STRING) { type = DataTypes.ASCII; } // X-Midas uses 'A' for all strings.

      if (DataTypes.DATA_TYPE_LIST.indexOf(type) >= 0) {
        len = XMidas.put_result(key, data.getBuf(), data.getBuf().length, 0, type, 0);
      } else {
        throw new MidasException("XmResultTable: Do not recognize Data type '"+type+"'.");
      }
    } else {
      key = "" + type + ":" + key;
      String val = nxm.sys.lib.Convert.o2s(value);
      len = XMidas.str2result(key, val, 0);
    }

    return (len > 0)? XMidas.rfind(key): null;
  }

  @Override
  public String[] getKeys() {
    StringBuffer sb = XMidas.getResultNames("*");
    Parser p = new Parser(sb.toString());
    return p.getArray(0);
  }

  @Override
  public String toString() {
    return "X-Midas ResultsTable";
  }
}
