"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFetchMoreRecords = void 0;
var _react = require("react");
var _types = require("../../../types");
var _use_data_state = require("../../hooks/use_data_state");
/*
 * 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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

/**
 * Params for the hook
 */

/**
 * Return type for the hook
 */

/**
 * Checks if more records can be loaded and returns a handler for it
 * @param isTextBasedQuery
 * @param stateContainer
 */
const useFetchMoreRecords = ({
  isTextBasedQuery,
  stateContainer
}) => {
  var _rows$raw$sort;
  const documents$ = stateContainer.dataState.data$.documents$;
  const totalHits$ = stateContainer.dataState.data$.totalHits$;
  const documentState = (0, _use_data_state.useDataState)(documents$);
  const totalHitsState = (0, _use_data_state.useDataState)(totalHits$);
  const rows = documentState.result || [];
  const isMoreDataLoading = documentState.fetchStatus === _types.FetchStatus.LOADING_MORE;
  const totalHits = totalHitsState.result || 0;
  const canFetchMoreRecords = !isTextBasedQuery && rows.length > 0 && totalHits > rows.length && Boolean((_rows$raw$sort = rows[rows.length - 1].raw.sort) === null || _rows$raw$sort === void 0 ? void 0 : _rows$raw$sort.length);
  const onFetchMoreRecords = (0, _react.useMemo)(() => canFetchMoreRecords ? () => {
    stateContainer.dataState.fetchMore();
  } : undefined, [canFetchMoreRecords, stateContainer.dataState]);
  return {
    isMoreDataLoading,
    totalHits,
    onFetchMoreRecords
  };
};
exports.useFetchMoreRecords = useFetchMoreRecords;