export const watch = function (
  SESSION_ID,
  key,
  type,
  info,
  result,
  condition,
  not_executed
) {
  if (!glb.DEBUG_MODE) return;
  var _session = SESSION_OBJ[SESSION_ID];
  if (!glb?.DEBUG_INFO_OBJ?.command?.watch?.[key]) return;
  var obj = glb.DEBUG_INFO_OBJ.command.watch[key];
  if (!obj) return;
  if (obj.type === type) {
    var result_str = "";

    if (typeof result !== "object") {
      result_str = " -> " + result;
    }

    var cond_label = "";
    if (condition) cond_label = "Condition:";
    else condition = "";
    if (!not_executed) {
      console.info(
        "%c Watch: " + obj.name + result_str,
        "color: dark-gray; font-weight: bold;",
        info,
        typeof result === "object" ? result : "",
        cond_label,
        condition
      );
    } else {
      console.info(
        "%c Watch: " + obj.name + result_str,
        "color: gray; font-weight: normal;",
        info,
        typeof result === "object" ? result : "",
        cond_label,
        condition,
        "- NOT EXECUTED !!"
      );
    }

    const watch_obj = {
      service: "watch_log",

      data: {
        name: obj.name,
        type: type,
        info: info,
        result: result,
        condition: condition,
        not_executed: not_executed,
      },
      id: STUDIO_WEBSOCKET_CONNECTION_ID,
      uid: _session.USR_OBJ._id,
      source: "runtime",
      app_id: _session.app_id,
      gtp_token: _session.gtp_token,
      app_token: _session.app_token,
    };
    if (
      typeof IS_DOCKER === "undefined" &&
      typeof IS_PROCESS_SERVER === "undefined" &&
      !glb.IS_WORKER
    ) {
      STUDIO_PEER_CONN_SEND_METHOD(watch_obj);
      // STUDIO_WEBSOCKET.emit("message", watch_obj);
    } else {
      func.utils.post_back_to_client(
        SESSION_ID,
        "send_watch_to_studio_websocket",
        _session.worker_id,
        watch_obj
      );
    }
  }
};
export const log = function (SESSION_ID, node_idP, jsonP) {
  if (typeof IS_PROCESS_SERVER !== "undefined") return;
  var _session = SESSION_OBJ[SESSION_ID];

  if (glb.DEBUG_MODE) {
    if (jsonP.error || jsonP.warning) {
      var desc =
        jsonP.action +
        (typeof jsonP.prop !== "undefined"
          ? "Prop: " + jsonP.prop.toString()
          : "") +
        (typeof jsonP.details !== "undefined" &&
        jsonP.details !== jsonP.prop.toString()
          ? " Result: " + jsonP.details.toString()
          : "");
      if (jsonP.error) {
        if (!glb.IS_WORKER)
          func.utils.alerts.toast(
            SESSION_ID,
            typeof jsonP.error !== "boolean" ? jsonP.error : "Error",
            desc,
            "error"
          );
        // console.log(jsonP);
        if (typeof jsonP.error !== "boolean") desc = jsonP.error + ": " + desc;
        console.info(
          "%c Error: " + desc,
          "color: red; font-weight: bold;",
          jsonP
        );
      }
      if (jsonP.warning) {
        if (!glb.IS_WORKER)
          func.utils.alerts.toast(
            SESSION_ID,
            typeof jsonP.warning !== "boolean" ? jsonP.warning : "Warning",
            desc,
            "warning"
          );

        if (typeof jsonP.warning !== "boolean")
          desc = jsonP.warning + ": " + desc;

        console.info(
          "%c Warring: " + desc,
          "color: orange; font-weight: bold;",
          jsonP
        );
        // console.log(jsonP);
      }
    }
  }

  //TRACE_ON
  if (jsonP.error || glb.TRACE_ON) {
    var d = new Date(); //.valueOf();
    var ms = d.getMilliseconds();
    var t =
      _.padStart((d.getHours() + 1).toString(), 2) +
      ":" +
      _.padStart((d.getMinutes() + 1).toString(), 2) +
      ":" +
      _.padStart(d.getSeconds().toString(), 2) +
      ":" +
      _.padStart(ms.toString(), 3);

    var json_new = _.assignIn(
      {
        node_id: node_idP,
        time: t,
      },
      jsonP
    );
    if (glb.DEBUG_MODE) {
      write(SESSION_ID, json_new);
    }
    if (glb.TRACE_ON) {
      let obj = {
        source: "runtime",
        service: "trace",
        client_id_from: _session.SYS_GLOBAL_OBJ_CLIENT_INFO.fingerprint,
        client_id_to: glb.TRACE_CLIENT_ID,
        data: json_new,
      };
      // if (CPI_WEBSOCKET) {
      //   // TBD move to peer
      //   CPI_WEBSOCKET.emit("message", obj);
      // }
    }
  }
};
export const write = function (SESSION_ID, logP) {
  var _session = SESSION_OBJ[SESSION_ID];
  const obj = {
    service: "debug_log",
    data: { data: logP },
    id: STUDIO_WEBSOCKET_CONNECTION_ID,
    session_id: SESSION_ID,
    uid: _session.USR_OBJ._id,
    source: "runtime",
    app_id: _session.app_id,
    gtp_token: _session.gtp_token,
    app_token: _session.app_token,

    ts: Date.now(),
  };
  if (_session.engine_mode === "live_preview") {
    if (
      typeof IS_DOCKER === "undefined" &&
      typeof IS_PROCESS_SERVER === "undefined" &&
      !glb.IS_WORKER
    ) {
      if (STUDIO_PEER_CONN_SEND_METHOD) STUDIO_PEER_CONN_SEND_METHOD(obj);
      // STUDIO_WEBSOCKET.emit("message", obj);
    } else if (glb.IS_WORKER) {
      func.utils.post_back_to_client(
        SESSION_ID,
        "write_debug_log",
        _session.worker_id,
        obj
      );
    }
  } else {
    console.log(logP);
  }
};

export const read_command = async function (data) {
  glb.DEBUG_INFO_OBJ.command = data;
  if (!glb.DEBUG_INFO_OBJ.command) return;
  if (glb.DEBUG_INFO_OBJ.command.log === "stop") {
    const module = await func.common.get_module(
      SESSION_ID,
      "xuda-live-preview-module.esm.js"
    );
    module.send_STUDIO_WEBSOCKET(SESSION_ID, "close");

    window.close();
    return;
  }

  $.each(WEB_WORKER[SESSION_ID], function (key, val) {
    if (
      RUNTIME_SERVER_WEBSOCKET &&
      RUNTIME_SERVER_WEBSOCKET_CONNECTED &&
      (!_session.opt.app_computing_mode ||
        _session.opt.app_computing_mode === "server")
    ) {
      var obj1 = {
        service: "update_debug_info",
        data: glb.DEBUG_INFO_OBJ,
        id: key,
      };
      WEB_WORKER[SESSION_ID][key].worker.emit("message", obj1);
    } else {
      WEB_WORKER[SESSION_ID][key].worker.postMessage({
        service: "update_debug_info",
        data: glb.DEBUG_INFO_OBJ,
        id: key,
      });
    }
  });
};
