package nxm.sys.net;

import nxm.sys.lib.Midas;
import nxm.sys.lib.Shell;
import nxm.sys.lib.Table;

/**
  Sends a message to a Macro to respond to an Http request.

  @author Jeff Schoen

*/
public class HMessage extends HSource {

  Midas M;
  private static boolean debug = false; // enable to turn on debug messages
  private static boolean useLegacyCode = false;

  /** HMessage Constructor
   *  @param name the name of the HMessage
   *  @param M    the Midas context
   */
  public HMessage (String name, Midas M) {
    if (!name.endsWith("/")) name += '/';
    this.name = name;
    this.M = M;
  }

  public void handleRequest (String uri, HPage hp) {
    if (debug) Shell.writeln("HMessage.handle() "+uri);
    if (!useLegacyCode) {
      int i = uri.indexOf('?');
      String s = uri.substring(i+1);
      Table tab = new Table(s);
      String name = tab.getS("NAME");
      int    info = tab.getL("INFO",0);
      Object data = tab.getO("DATA");
      M.macro.queue.put(name,info,data);
      hp.setContentType("text/plain");
      hp.open();
      hp.write("MSG?"+s);
      hp.close();
    }
    else {
      Table tab = new Table();
      tab.put("URI",uri);
      tab.put("HPAGE",hp);
      M.macro.queue.put("HREQUEST",0,tab);
    }

  }

  /** Use legacy HMessage message / code
   *  @param useLegacyCode use legacy HMessage message / code
   */
  public static void setUseLegacyCode(boolean useLegacyCode) {
    HMessage.useLegacyCode = useLegacyCode;
  }

  /** Get if we are using legacy code / message
   *  @return if legacy code is being used
   */
  public static boolean getUseLegacyCode() {
    return HMessage.useLegacyCode;
  }

}
