"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.recursivelyFetchEngines = void 0;
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const recursivelyFetchEngines = ({
  endpoint,
  onComplete,
  query = {},
  pageSize = 25
}) => {
  const {
    http
  } = _http.HttpLogic.values;
  let enginesAccumulator = [];
  const fetchEngines = async (page = 1) => {
    try {
      const {
        meta,
        results
      } = await http.get(endpoint, {
        query: {
          'page[current]': page,
          'page[size]': pageSize,
          ...query
        }
      });
      enginesAccumulator = [...enginesAccumulator, ...results];
      if (page >= meta.page.total_pages) {
        onComplete(enginesAccumulator);
      } else {
        fetchEngines(page + 1);
      }
    } catch (e) {
      (0, _flash_messages.flashAPIErrors)(e);
    }
  };
  fetchEngines();
};
exports.recursivelyFetchEngines = recursivelyFetchEngines;