package nxm.sys.test;

import nxm.sys.lib.Data;
import nxm.sys.lib.DataFile;
import nxm.sys.lib.Primitive;

/** Class to test the new isReady(..) methods added for BUG 2094.
    <br><br>
    Sample usage:
      <pre>
        nM&gt; wave temp_wave.prm form=sb elem=6k
        nM&gt; nxm.sys.test.isreadytester/broken=t in=test_wave.prm
        ... execution should hang after reading 4096 bytes...

        nM&gt; isreadytester/broken=f temp_wave.prm
        ... execution should not hang (will output -1 when it reaches the EOF) ...
      </pre>

    @author JC4
 */
public class isreadytester extends Primitive {
  private DataFile inFile;
  private Data     inBuf;
  private boolean  broken; // switch to test before /after code changes

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

  @Override
  public int open () {
    inFile = MA.getDataFile("IN");
    inFile.open();
    inBuf = inFile.getDataBuffer(4096);
    broken = MA.getState("/BROKEN");
    return NORMAL;
  }

  @Override
  public int process () {
    if (broken) {
      if (inFile.avail() < inBuf.getSize())  return NOOP;
    }
    else {
      if (!inFile.isReady(inBuf.getSize())) return NOOP;
    }
    int numRead = inFile.read(inBuf);
    M.info("Read "+numRead+" elements");

    return (numRead <= 0) ? FINISH: NORMAL;
  }

  @Override
  public int close () {
    inFile.close();
    return NORMAL;
  }
}
