package nxm.sys.intr;

import nxm.sys.lib.BaseFile;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.TextFile;

/** Re-directs output to a file OR as a "TEXT" message to a command.

  @author Eduardo Gamez
  @author Neon Ngo - fixed bugs and properly support "TO" function (Since 2.9.3 for BUG 2422)
*/
public class Archive extends Intrinsic {

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

  @SuppressWarnings("deprecation")  // for M.terminal - since 3.7.1 for NXM-2813
  public int process () {

    // get parameters
    String function = MA.getU("FUNC");
    String filename = MA.getU("FILE");
    boolean echo    = MA.getState("/ECHO", true);

    // close out old archive file
    if (M.terminal.archiver != null) {
      M.terminal.archiver.close();
      M.terminal.archiver = null;
    }

    // close out old TO messager
    if (M.terminal.messager != null) {
      M.terminal.messager = null;
    }

    // set terminal's echo setting
    M.terminal.echo = echo;

    if (function.equals("ON")) {                 // start new archive file
      TextFile tf = MA.getTextFile("FILE");
      if (!tf.open(BaseFile.OUTPUT|BaseFile.NOABORT)) {
        M.warning("ARCHIVE: Unable to open (for output) " + tf.getName());
      } else {
        M.terminal.archiver = tf;
      }
    }
    else if (function.equals("TO")) {            // start new archive TO command
      M.terminal.messager = M.registry.getCommand(filename, 5);
      if (M.terminal.messager==null) M.error("Messager "+filename+" not found");
    }

    return FINISH;
  }
}
