const _this = {};

export const init_module = (e) => {
  _this.func = e.func;
  _this.glb = e.glb;
  _this.SESSION_OBJ = e.SESSION_OBJ;
  _this.APP_OBJ = e.APP_OBJ;
  _this.IS_DOCKER = e.IS_DOCKER;
  _this.IS_API_SERVER = e.IS_API_SERVER;
  _this.IS_PROCESS_SERVER = e.IS_PROCESS_SERVER;
};
export const peer_actions = async function (SESSION_ID, conn_send, data) {
  var _session = _this.SESSION_OBJ[SESSION_ID];
  const take_screenshot = async function (service) {
    await _this.func.utils.load_js_on_demand(
      "https://html2canvas.hertzen.com/dist/html2canvas.js"
    );
    html2canvas(document.body).then((canvas) => {
      conn_send({
        service,
        data: canvas.toDataURL("image/png"),
        id: data.id,
        uid: _session.USR_OBJ._id,
        source: "runtime",
        app_id: _session.app_id,
        gtp_token: _session.gtp_token,
        app_token: _session.app_token,

        session_id: SESSION_ID,
        ts: Date.now(),
        session: {
          SYS_GLOBAL_OBJ_CLIENT_INFO:
            _this.SESSION_OBJ[SESSION_ID].SYS_GLOBAL_OBJ_CLIENT_INFO,
        },
      });
    });
  };

  switch (data.service) {
    case "send_object_to_runtime": {
      if (STUDIO_WEBSOCKET_CONNECTION_ID === data.data.connection_id) {
        if (RESPONSE_FROM_STUDIO_QUEUE[data.data.req_id]) {
          RESPONSE_FROM_STUDIO_QUEUE[data.data.req_id].data = data.data;
        }
      }
      break;
    }

    case "live_preview_element_reference":
    case "live_preview_element_info":
    case "live_preview_element_dnd": {
      if (data.data.action === "on") {
        _this.func.UI.utils.live_preview_element_inspect_off();
        _this.func.UI.utils.live_preview_element_inspect_on(
          SESSION_ID,
          data.service
        );
      } else {
        _this.func.UI.utils.live_preview_element_inspect_off();
      }

      break;
    }

    case "live_preview_show_selected_element": {
      _this.func.UI.utils.live_preview_show_selected_element(data.data.nodeid);
      break;
    }

    case "live_preview_cmd_execute": {
      let res;
      try {
        res = { data: eval(data.data.execute) };
      } catch (e) {
        res = { data: e.message, error: true };
      }
      conn_send({
        service: "debug_log",
        data: res,
        id: data.id,
        uid: _session.USR_OBJ._id,
        source: "runtime",
        app_id: _session.app_id,
        session_id: SESSION_ID,
        gtp_token: _session.gtp_token,
        app_token: _session.app_token,

        ts: Date.now(),
      });
      break;
    }

    case "live_preview_hard_reload": {
      await func.index.delete_pouch(SESSION_ID);
      location.reload();

      break;
    }

    case "live_preview_screenshot": {
      await take_screenshot("live_preview_screenshot_captured");
      break;
    }

    case "live_preview_get_session": {
      let _session = _.cloneDeep(_this.SESSION_OBJ[SESSION_ID]);
      for (const [key, val] of Object.entries(_session.DS_GLB)) {
        _session.DS_GLB[key] = await func.utils.clean_returned_datasource(
          SESSION_ID,
          key
        );
      }
      delete _session.root_element;
      delete _session.WORKER_OBJ;

      conn_send({
        service: "live_preview_session_result",
        data: _session,
        id: data.id,
        uid: _session.USR_OBJ._id,
        source: "runtime",
        app_id: _session.app_id,
        session_id: SESSION_ID,
        gtp_token: _session.gtp_token,
        app_token: _session.app_token,

        ts: Date.now(),
      });
      break;
    }

    case "live_preview_screen_share_start": {
      _this.live_preview_screen_share_interval = setInterval(async () => {
        await take_screenshot("live_preview_screen_share");
      }, 500);
      break;
    }

    case "live_preview_screen_share_end": {
      clearInterval(_this.live_preview_screen_share_interval);
      break;
    }

    case "live_preview_connected": {
      $(_session.root_element).addClass("live_preview_online");
      break;
    }

    case "live_preview_disconnected": {
      $(_session.root_element).removeClass("live_preview_online");
      break;
    }
    case "live_preview_kickoff": {
      _session.opt.live_token_stat = 2;
      func.UI.utils.progressScreen.show(
        SESSION_ID,
        "Session closed by the host",
        false,
        true
      );

      break;
    }

    case "document_changed": {
      console.log("document_changed", data);

      func.UI.screen.refresh_document_changes_for_realtime_update(
        SESSION_ID,
        data.data
      );
      // for (const [key, ds] of Object.entries(_session.DS_GLB)) {
      //   let prog_obj = await func.utils.VIEWS_OBJ.get(SESSION_ID, ds.prog_id);
      //   if (
      //     prog_obj?.progDataSource?.dataSourceRealtime &&
      //     prog_obj?.progDataSource?.dataSourceTableId === data.data.table_id
      //   ) {
      //     if (ds.data_feed.rows[data.data.row_id]) {
      //       console.log(
      //         "ds.data_feed.rows[data.row_id]",
      //         ds.data_feed.rows[data.data.row_id]
      //       );
      //       // func.UI.screen.refresh_screen(SESSION_ID, null, key);
      //       func.action.execute(SESSION_ID, "act_refresh", ds, null, null);
      //     }
      //   }
      // }

      break;
    }

    case "live_preview_get_obj_response": {
      if (!data?.data?._id) return;
      $("body").trigger("live_preview_get_obj_response_" + data.data._id, {
        data: data.data,
      });
      break;
    }
    case "rpi_request_response": {
      $("body").trigger("rpi_request_response_" + data.req_id, {
        data: data.data,
      });
      break;
    }
    case "ping": {
      conn_send({
        service: "pong",
        data: {},
        id: data.id,
        uid: _session.USR_OBJ._id,
        source: "runtime",
        app_id: _session.app_id,
        session_id: SESSION_ID,
        gtp_token: _session.gtp_token,
        app_token: _session.app_token,

        ts: Date.now(),
      });

      break;
    }

    case "studio_doc_saved": {
      // console.log("studio_doc_saved", data);
      var _session = SESSION_OBJ[SESSION_ID];
      DOCS_OBJ[_session.app_id][data.data._id] = data.data;
      func.UI.screen.live_preview_hot_module_reload(SESSION_ID, data.data);
      break;
    }
    default:
      break;
  }
};
