"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useData = void 0;
var _react = require("react");
var _rxjs = require("rxjs");
var _public = require("@kbn/kibana-react-plugin/public");
var _mlDatePicker = require("@kbn/ml-date-picker");
var _common = require("../../common");
var _use_time_buckets = require("./use_time_buckets");
var _use_aiops_app_context = require("./use_aiops_app_context");
var _use_document_count_stats = require("./use_document_count_stats");
/*
 * 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 DEFAULT_BAR_TARGET = 75;
const useData = (selectedDataView, contextId, searchQuery, onUpdate, selectedSignificantTerm, selectedGroup = null, barTarget = DEFAULT_BAR_TARGET, timeRange) => {
  const {
    executionContext
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  (0, _public.useExecutionContext)(executionContext, {
    name: _common.PLUGIN_ID,
    type: 'application',
    id: contextId
  });
  const [lastRefresh, setLastRefresh] = (0, _react.useState)(0);
  const _timeBuckets = (0, _use_time_buckets.useTimeBuckets)();
  const timefilter = (0, _mlDatePicker.useTimefilter)({
    timeRangeSelector: (selectedDataView === null || selectedDataView === void 0 ? void 0 : selectedDataView.timeFieldName) !== undefined,
    autoRefreshSelector: true
  });
  const fieldStatsRequest = (0, _react.useMemo)(() => {
    const timefilterActiveBounds = timeRange !== null && timeRange !== void 0 ? timeRange : timefilter.getActiveBounds();
    if (timefilterActiveBounds !== undefined) {
      var _timefilterActiveBoun, _timefilterActiveBoun2, _timeBuckets$getInter;
      _timeBuckets.setInterval('auto');
      _timeBuckets.setBounds(timefilterActiveBounds);
      _timeBuckets.setBarTarget(barTarget);
      return {
        earliest: (_timefilterActiveBoun = timefilterActiveBounds.min) === null || _timefilterActiveBoun === void 0 ? void 0 : _timefilterActiveBoun.valueOf(),
        latest: (_timefilterActiveBoun2 = timefilterActiveBounds.max) === null || _timefilterActiveBoun2 === void 0 ? void 0 : _timefilterActiveBoun2.valueOf(),
        intervalMs: (_timeBuckets$getInter = _timeBuckets.getInterval()) === null || _timeBuckets$getInter === void 0 ? void 0 : _timeBuckets$getInter.asMilliseconds(),
        index: selectedDataView.getIndexPattern(),
        searchQuery,
        timeFieldName: selectedDataView.timeFieldName,
        runtimeFieldMap: selectedDataView.getRuntimeMappings()
      };
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lastRefresh, searchQuery, timeRange]);
  const overallStatsRequest = (0, _react.useMemo)(() => {
    return fieldStatsRequest ? {
      ...fieldStatsRequest,
      selectedSignificantTerm,
      selectedGroup,
      includeSelectedSignificantTerm: false
    } : undefined;
  }, [fieldStatsRequest, selectedSignificantTerm, selectedGroup]);
  const selectedSignificantTermStatsRequest = (0, _react.useMemo)(() => {
    return fieldStatsRequest && (selectedSignificantTerm || selectedGroup) ? {
      ...fieldStatsRequest,
      selectedSignificantTerm,
      selectedGroup,
      includeSelectedSignificantTerm: true
    } : undefined;
  }, [fieldStatsRequest, selectedSignificantTerm, selectedGroup]);
  const documentStats = (0, _use_document_count_stats.useDocumentCountStats)(overallStatsRequest, selectedSignificantTermStatsRequest, lastRefresh);
  (0, _react.useEffect)(() => {
    const timefilterUpdateSubscription = (0, _rxjs.merge)(timefilter.getAutoRefreshFetch$(), timefilter.getTimeUpdate$(), _mlDatePicker.mlTimefilterRefresh$).subscribe(() => {
      if (onUpdate) {
        onUpdate({
          time: timefilter.getTime(),
          refreshInterval: timefilter.getRefreshInterval()
        });
        setLastRefresh(Date.now());
      }
    });

    // This listens just for an initial update of the timefilter to be switched on.
    const timefilterEnabledSubscription = timefilter.getEnabledUpdated$().subscribe(() => {
      if (fieldStatsRequest === undefined) {
        setLastRefresh(Date.now());
      }
    });
    return () => {
      timefilterUpdateSubscription.unsubscribe();
      timefilterEnabledSubscription.unsubscribe();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return {
    documentStats,
    timefilter,
    /** Start timestamp filter */
    earliest: fieldStatsRequest === null || fieldStatsRequest === void 0 ? void 0 : fieldStatsRequest.earliest,
    /** End timestamp filter */
    latest: fieldStatsRequest === null || fieldStatsRequest === void 0 ? void 0 : fieldStatsRequest.latest,
    intervalMs: fieldStatsRequest === null || fieldStatsRequest === void 0 ? void 0 : fieldStatsRequest.intervalMs,
    forceRefresh: () => setLastRefresh(Date.now())
  };
};
exports.useData = useData;