package nxm.sys.test;

import nxm.sys.inc.InternalUseOnly;
import nxm.sys.inc.MessageHandler;
import nxm.sys.lib.Message;
import nxm.sys.lib.Primitive;
import nxm.sys.lib.Time;

/** A simple primitive used by %test_message that will echo back messages to the
    sender but with INFO= changed. Usage:
    <pre>
      nxm.sys.test.message_echo COUNT=[count] INFO=[info] WAIT=[wait]

      COUNT=    - Number of messages to wait for before exiting.
      INFO=     - Value to put in the message info field before sending back.
      WAIT=     - Maximum number of seconds to wait for messages to arrive
                  before exiting.
    </pre>

    @author  J. Czechowski IV
 */
@InternalUseOnly
public class message_echo extends Primitive {
  private int    info;
  private int    count;
  private double endTime;

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

  @Override
  public int open () {
    info    = MA.getL("INFO",  1);
    count   = MA.getL("COUNT", 1);
    endTime = MA.getD("WAIT",  5) + Time.current();
    return NORMAL;
  }

  @Override
  public int process () {
    if ((Time.current() >= endTime) || (count <= 0)) {
      return FINISH;
    }
    return SLEEP;
  }

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

  @Override
  public int processMessage (Message msg) {
    if (msg.getName().startsWith("MSG_TEST")) {
      MessageHandler src = (MessageHandler)msg.getFrom();
      msg.setInfo(info);
      msg.setTo(src);
      msg.setFrom(this);
      src.processMessage(msg);
      return NORMAL;
    }
    else {
      return super.processMessage(msg);
    }
  }
}
