package nxm.sys.intr;

import nxm.sys.lib.FileName;
import nxm.sys.lib.Intrinsic;
import nxm.sys.lib.Logger;

/**
  Reports INFO/WARNING/ERROR messages to a display and/or file.
  <br>
  TBD: Also converts reports to different presentations.

  @author Jeff Schoen
*/
public class Report extends Intrinsic {

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

  public int process() {

    // get parameters
    String func = MA.getU("FUNC");

    if (func.equals("ON")) {
      FileName fname = MA.getFileName("FILE");
      final Logger prevLogger = M.logger;
      if (prevLogger != null) {
        // since 3.5.4, send notice to previous logger that it is getting replaced (BUG 2870)
        fname.setExt("mlog"); // matches logic in Logger.open(.) to show actual new log file name and it's extension
        // TODO: maybe upgrade to this from INFO to WARN in next beta series, e.g. 3.7.0+
        M.info("Existing M.logger is being replaced by REPORT ON " + fname + " -> " + M);
        prevLogger.close();
      }
      M.logger = new Logger(M);
      M.logger.open(fname);
    }
    else if (func.equals("FLUSH")) {
      if (M.logger==null) return FINISH;
      M.logger.flush();
    }
    else if (func.equals("OFF")) {
      if (M.logger==null) return FINISH;
      M.info("Existing M.logger is being disabled by REPORT OFF -> " + M);     // since 3.5.4 as part of BUG 2870
      M.logger.close();
      M.logger = null;
    }
    else if (func.equals("AUTOSAVE")) {
      Logger.setAutoSave( MA.getState("FILE",true) );
    }
    else if (func.equals("SAVEOFF")) {
      if (M.logger==null) return FINISH;
      M.info("Existing M.logger is being disabled by REPORT SAVEOFF -> " + M); // since 3.5.4 as part of BUG 2870
      M.logger.close();
      M.logger.saveOff();
      M.logger = null;
    }
    else M.error("Unsupported LOGGER function: "+func);

    return FINISH;
  }
}
