export const loader = async function (SESSION_ID) {
  const db = await func.utils.connect_pouchdb(SESSION_ID);
  var _session = SESSION_OBJ[SESSION_ID];
  try {
    const response = await fetch(
      `https://${_session.domain}/${_session.app_id}_startup_data.${
        _session?.opt?.app_build_id?.toString() || "0"
      }.json`,
      {
        method: "GET",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      }
    );

    if (!response.ok) {
      glb.register_startup_programs = true;
      return;
      //   throw new Error(response);
    }

    const json = await response.json();

    // console.log(json);

    ///////////////////
    db.put({
      _id: `cache_rt_info`,
      data: { code: 1, data: json.rt_info_obj },
      docType: "cache_app",
    });

    ////////////////////
    for await (const [plugin_name, val] of Object.entries(json.plugins_setup)) {
      await db.put({
        _id: `cache_plugin_setup_${plugin_name}`,
        data: val,
        docType: "cache_plugin",
      });
    }

    ////////////////////
    const loader_module = await func.common.get_module(
      SESSION_ID,
      `xuda-progs-loader-module.mjs`
    );

    for await (const [prog_id, val] of Object.entries(json.docs_obj)) {
      await loader_module.save_objects_cache(
        SESSION_ID,
        prog_id,
        "DOCS_OBJ",
        val
      );
    }

    setTimeout(() => {
      for (let prog_id of [
        ...json.rt_info_obj?.accessible_deployed_progs_arr,
        ...json.rt_info_obj?.accessible_deployed_tables_arr,
      ] || []) {
        loader_module.DOCS_OBJ_get(SESSION_ID, prog_id);
      }
    }, 20000);

    return json;
  } catch (err) {
    console.warn(err.message);
  }
};
