package nxm.sys.test;

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

/** Utility class for testing issues that are periodic with respect to transfer length.
    This sends a NeXtMidas message (with the specified name and data) at the specified
    rate, allowing the test macro to take the appropriate action at the appropriate time.<br>

    Note: Input file data is not used directly, but only for to match the messages with
    the data rate.

    @author  Jeanette McCall
    @since   NeXtMidas 3.9.0
*/

public class msgsender extends Primitive {

  private DataFile hi;      // Input data source (used for message rate)
  private Data data;        // Data buffer for storing data (determining how much data was available)
  private String msgName;   // Name of message to send
  private int    msgRate;   // Message rate based on transfer length
  private Object msgData;   // Message Data
  private int    count = 0; // Modulo based count used for determining when to send out message

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

  @Override
  public int open() {
    hi = MA.getDataFile ("IN");
    hi.open();
    msgName     = MA.getS("NAME", "TESTMSG");
    msgRate     = MA.getL("RATE", 1);
    msgData     = MA.getS("DATA", "This is a message from message sender");

    xfer = Math.max(1,(int)(bufSize/hi.dbpe));
    xfer = MA.getL("/TL",xfer);
    data = hi.getDataBuffer(xfer);

    return NORMAL;
  }

  @Override
  public int process() {
    int    status = NORMAL;
    int n = hi.read(data);
    if (n>0) {
      status = NORMAL;
      count = (count+1)  % msgRate;
      if (count == 0) {
        Message msg = new Message(msgName,0,msgData,null,this,null);
        super.sendMessage(msg);
      }
    }
    else if (n==0) status = NOOP;
    else status = FINISH;
    return status;
  }

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

