const promiseChunks = require('../../utils/translations/promiseChunks');

const getItemManifest = require('./getItemManifest');

/**
 * @param {string} url
 * @param {Object.<string, *>} params
 * @param {[]} items
 * @param {{batchSize: number, delayMs: number, spinner: Function}} options
 * @returns {Promise<Record<string, *>[]>}
 */
async function getAllItemManifests(url, params, items, options) {
  const { spinner, ...chunkOptions } = options;
  let itemsFinished = 0;

  const itemManifests = await promiseChunks(
    items,
    ({ id }) =>
      getItemManifest(url, params, id)
        // Middleware for checking if task finished or failed
        .then((data) => {
          itemsFinished += 1;
          spinner(`Getting item data [${itemsFinished}/${items.length}]`);
          return data;
        }),
    chunkOptions,
  );

  if (!itemManifests) {
    spinner(false);
    throw new Error('No items found');
  }

  return itemManifests;
}

module.exports = getAllItemManifests;
