"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFetchOccurrencesRange = void 0;
var _react = require("react");
var _rxjs = require("rxjs");
var _esQuery = require("@kbn/es-query");
var _common = require("@kbn/data-plugin/common");
var _is_text_based_query = require("../../../utils/is_text_based_query");
/*
 * 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.
 */

const useFetchOccurrencesRange = params => {
  const data = params.services.data;
  const uiSettings = params.services.uiSettings;
  const [range, setRange] = (0, _react.useState)(undefined);
  const abortControllerRef = (0, _react.useRef)(null);
  const mountedRef = (0, _react.useRef)(true);
  const fetchOccurrences = (0, _react.useCallback)(async (dataView, query, filters) => {
    let occurrencesRange = null;
    if (dataView !== null && dataView !== void 0 && dataView.isTimeBased() && query && mountedRef.current) {
      var _abortControllerRef$c;
      (_abortControllerRef$c = abortControllerRef.current) === null || _abortControllerRef$c === void 0 ? void 0 : _abortControllerRef$c.abort();
      abortControllerRef.current = new AbortController();
      try {
        var _abortControllerRef$c2;
        const dslQuery = (0, _esQuery.buildEsQuery)(dataView, query !== null && query !== void 0 ? query : [], filters !== null && filters !== void 0 ? filters : [], (0, _common.getEsQueryConfig)(uiSettings));
        occurrencesRange = await fetchDocumentsTimeRange({
          data,
          dataView,
          dslQuery,
          abortSignal: (_abortControllerRef$c2 = abortControllerRef.current) === null || _abortControllerRef$c2 === void 0 ? void 0 : _abortControllerRef$c2.signal
        });
      } catch (error) {
        //
      }
    }
    if (mountedRef.current) {
      setRange(occurrencesRange);
    }
    return occurrencesRange;
  }, [abortControllerRef, setRange, mountedRef, data, uiSettings]);
  (0, _react.useEffect)(() => {
    return () => {
      var _abortControllerRef$c3;
      mountedRef.current = false;
      (_abortControllerRef$c3 = abortControllerRef.current) === null || _abortControllerRef$c3 === void 0 ? void 0 : _abortControllerRef$c3.abort();
    };
  }, [abortControllerRef, mountedRef]);
  (0, _react.useEffect)(() => {
    if (!(0, _is_text_based_query.isTextBasedQuery)(params.query)) {
      fetchOccurrences(params.dataView, params.query, params.filters);
    }
  }, [fetchOccurrences, params.query, params.filters, params.dataView]);
  return {
    range,
    refetch: () => fetchOccurrences(params.dataView, params.query, params.filters)
  };
};
exports.useFetchOccurrencesRange = useFetchOccurrencesRange;
async function fetchDocumentsTimeRange({
  data,
  dataView,
  dslQuery,
  abortSignal
}) {
  var _result$rawResponse, _result$rawResponse$a, _result$rawResponse$a2, _result$rawResponse2, _result$rawResponse2$, _result$rawResponse2$2;
  if (!(dataView !== null && dataView !== void 0 && dataView.timeFieldName)) {
    return null;
  }
  const result = await (0, _rxjs.lastValueFrom)(data.search.search({
    params: {
      index: dataView.getIndexPattern(),
      size: 0,
      body: {
        query: dslQuery !== null && dslQuery !== void 0 ? dslQuery : {
          match_all: {}
        },
        aggs: {
          earliest_timestamp: {
            min: {
              field: dataView.timeFieldName
            }
          },
          latest_timestamp: {
            max: {
              field: dataView.timeFieldName
            }
          }
        }
      }
    }
  }, {
    abortSignal
  }));
  const earliestTimestamp = (_result$rawResponse = result.rawResponse) === null || _result$rawResponse === void 0 ? void 0 : (_result$rawResponse$a = _result$rawResponse.aggregations) === null || _result$rawResponse$a === void 0 ? void 0 : (_result$rawResponse$a2 = _result$rawResponse$a.earliest_timestamp) === null || _result$rawResponse$a2 === void 0 ? void 0 : _result$rawResponse$a2.value_as_string;
  const latestTimestamp = (_result$rawResponse2 = result.rawResponse) === null || _result$rawResponse2 === void 0 ? void 0 : (_result$rawResponse2$ = _result$rawResponse2.aggregations) === null || _result$rawResponse2$ === void 0 ? void 0 : (_result$rawResponse2$2 = _result$rawResponse2$.latest_timestamp) === null || _result$rawResponse2$2 === void 0 ? void 0 : _result$rawResponse2$2.value_as_string;
  return earliestTimestamp && latestTimestamp ? {
    from: earliestTimestamp,
    to: latestTimestamp
  } : null;
}