"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChangePointDetectionControlsContextProvider = exports.ChangePointDetectionControlsContext = exports.ChangePointDetectionContextProvider = exports.ChangePointDetectionContext = void 0;
exports.useChangePointDetectionContext = useChangePointDetectionContext;
exports.useChangePointDetectionControlsContext = void 0;
exports.useRequestParams = useRequestParams;
var _react = _interopRequireWildcard(require("react"));
var _rxjs = require("rxjs");
var _mlUrlState = require("@kbn/ml-url-state");
var _mlDatePicker = require("@kbn/ml-date-picker");
var _fieldTypes = require("@kbn/field-types");
var _use_filters_query = require("../../hooks/use_filters_query");
var _constants = require("./constants");
var _search_utils = require("../../application/utils/search_utils");
var _use_aiops_app_context = require("../../hooks/use_aiops_app_context");
var _use_data_source = require("../../hooks/use_data_source");
var _use_time_buckets = require("../../hooks/use_time_buckets");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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 ChangePointDetectionContext = /*#__PURE__*/(0, _react.createContext)({
  splitFieldsOptions: [],
  metricFieldOptions: [],
  requestParams: {},
  timeBuckets: {},
  bucketInterval: {},
  updateRequestParams: () => {},
  resultFilters: [],
  updateFilters: () => {},
  resultQuery: {
    query: '',
    language: 'kuery'
  },
  combinedQuery: {},
  selectedChangePoints: {},
  setSelectedChangePoints: () => {}
});
exports.ChangePointDetectionContext = ChangePointDetectionContext;
const ChangePointDetectionControlsContext = /*#__PURE__*/(0, _react.createContext)({
  splitFieldsOptions: [],
  metricFieldOptions: []
});
exports.ChangePointDetectionControlsContext = ChangePointDetectionControlsContext;
const useChangePointDetectionControlsContext = () => {
  return (0, _react.useContext)(ChangePointDetectionControlsContext);
};
exports.useChangePointDetectionControlsContext = useChangePointDetectionControlsContext;
const ChangePointDetectionControlsContextProvider = ({
  children
}) => {
  const {
    dataView
  } = (0, _use_data_source.useDataSource)();
  const metricFieldOptions = (0, _react.useMemo)(() => {
    return dataView.fields.filter(({
      aggregatable,
      type
    }) => aggregatable && type === 'number');
  }, [dataView]);
  const splitFieldsOptions = (0, _react.useMemo)(() => {
    return dataView.fields.filter(({
      aggregatable,
      esTypes,
      displayName
    }) => aggregatable && esTypes && esTypes.some(el => [_fieldTypes.ES_FIELD_TYPES.KEYWORD, _fieldTypes.ES_FIELD_TYPES.IP].includes(el)) && !['_id', '_index'].includes(displayName));
  }, [dataView]);
  const value = {
    metricFieldOptions,
    splitFieldsOptions
  };
  return /*#__PURE__*/_react.default.createElement(ChangePointDetectionControlsContext.Provider, {
    value: value
  }, children);
};
exports.ChangePointDetectionControlsContextProvider = ChangePointDetectionControlsContextProvider;
const ChangePointDetectionContextProvider = ({
  children
}) => {
  const {
    dataView,
    savedSearch
  } = (0, _use_data_source.useDataSource)();
  const {
    uiSettings,
    data: {
      query: {
        filterManager
      }
    }
  } = (0, _use_aiops_app_context.useAiopsAppContext)();
  const savedSearchQuery = (0, _react.useMemo)(() => {
    return (0, _search_utils.getEsQueryFromSavedSearch)({
      dataView,
      uiSettings,
      savedSearch,
      filterManager
    });
  }, [dataView, savedSearch, uiSettings, filterManager]);
  const timefilter = (0, _mlDatePicker.useTimefilter)();
  const timeBuckets = (0, _use_time_buckets.useTimeBuckets)();
  const [resultFilters, setResultFilter] = (0, _react.useState)([]);
  const [selectedChangePoints, setSelectedChangePoints] = (0, _react.useState)({});
  const [bucketInterval, setBucketInterval] = (0, _react.useState)();
  const timeRange = (0, _mlDatePicker.useTimeRangeUpdates)(true);
  (0, _react.useEffect)(function updateIntervalOnTimeBoundsChange() {
    const timeUpdateSubscription = timefilter.getTimeUpdate$().pipe((0, _rxjs.startWith)(timefilter.getTime())).subscribe(() => {
      const activeBounds = timefilter.getActiveBounds();
      if (!activeBounds) {
        throw new Error('Time bound not available');
      }
      timeBuckets.setInterval('auto');
      timeBuckets.setBounds(activeBounds);
      setBucketInterval(timeBuckets.getInterval());
    });
    return () => {
      timeUpdateSubscription.unsubscribe();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const metricFieldOptions = (0, _react.useMemo)(() => {
    return dataView.fields.filter(({
      aggregatable,
      type
    }) => aggregatable && type === 'number');
  }, [dataView]);
  const splitFieldsOptions = (0, _react.useMemo)(() => {
    return dataView.fields.filter(({
      aggregatable,
      esTypes,
      displayName
    }) => aggregatable && esTypes && esTypes.some(el => [_fieldTypes.ES_FIELD_TYPES.KEYWORD, _fieldTypes.ES_FIELD_TYPES.IP].includes(el)) && !['_id', '_index'].includes(displayName));
  }, [dataView]);
  const [requestParamsFromUrl, updateRequestParams] = (0, _mlUrlState.usePageUrlState)('changePoint');
  const resultQuery = (0, _react.useMemo)(() => {
    var _requestParamsFromUrl, _savedSearchQuery$sea, _savedSearchQuery$que;
    return (_requestParamsFromUrl = requestParamsFromUrl.query) !== null && _requestParamsFromUrl !== void 0 ? _requestParamsFromUrl : {
      query: (_savedSearchQuery$sea = savedSearchQuery === null || savedSearchQuery === void 0 ? void 0 : savedSearchQuery.searchString) !== null && _savedSearchQuery$sea !== void 0 ? _savedSearchQuery$sea : '',
      language: (_savedSearchQuery$que = savedSearchQuery === null || savedSearchQuery === void 0 ? void 0 : savedSearchQuery.queryLanguage) !== null && _savedSearchQuery$que !== void 0 ? _savedSearchQuery$que : 'kuery'
    };
  }, [savedSearchQuery, requestParamsFromUrl.query]);
  const requestParams = (0, _react.useMemo)(() => {
    const params = {
      ...requestParamsFromUrl
    };
    if (!params.fieldConfigs) {
      var _metricFieldOptions$;
      params.fieldConfigs = [{
        fn: _constants.DEFAULT_AGG_FUNCTION,
        metricField: (_metricFieldOptions$ = metricFieldOptions[0]) === null || _metricFieldOptions$ === void 0 ? void 0 : _metricFieldOptions$.name
      }];
    }
    params.interval = bucketInterval === null || bucketInterval === void 0 ? void 0 : bucketInterval.expression;
    return params;
  }, [requestParamsFromUrl, metricFieldOptions, bucketInterval]);
  const updateFilters = (0, _react.useCallback)(update => {
    filterManager.setFilters(update);
  }, [filterManager]);
  (0, _react.useEffect)(() => {
    setResultFilter(filterManager.getFilters());
    const sub = filterManager.getUpdates$().subscribe(() => {
      setResultFilter(filterManager.getFilters());
    });
    return () => {
      sub.unsubscribe();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(function syncFilters() {
    const globalFilters = filterManager === null || filterManager === void 0 ? void 0 : filterManager.getGlobalFilters();
    if (requestParamsFromUrl.filters) {
      filterManager.setFilters(requestParamsFromUrl.filters);
    }
    if (globalFilters) {
      filterManager === null || filterManager === void 0 ? void 0 : filterManager.addFilters(globalFilters);
    }
  }, [requestParamsFromUrl.filters, filterManager]);
  const combinedQuery = (0, _react.useMemo)(() => {
    var _mergedQuery$bool;
    const mergedQuery = (0, _search_utils.createMergedEsQuery)(resultQuery, resultFilters, dataView, uiSettings);
    if (!Array.isArray((_mergedQuery$bool = mergedQuery.bool) === null || _mergedQuery$bool === void 0 ? void 0 : _mergedQuery$bool.filter)) {
      if (!mergedQuery.bool) {
        mergedQuery.bool = {};
      }
      mergedQuery.bool.filter = [];
    }
    mergedQuery.bool.filter.push({
      range: {
        [dataView.timeFieldName]: {
          from: timeRange.from,
          to: timeRange.to
        }
      }
    });
    return mergedQuery;
  }, [resultFilters, resultQuery, uiSettings, dataView, timeRange]);
  if (!bucketInterval) return null;
  const value = {
    timeBuckets,
    requestParams,
    updateRequestParams,
    metricFieldOptions,
    splitFieldsOptions,
    bucketInterval,
    resultFilters,
    updateFilters,
    resultQuery,
    combinedQuery,
    selectedChangePoints,
    setSelectedChangePoints
  };
  return /*#__PURE__*/_react.default.createElement(ChangePointDetectionContext.Provider, {
    value: value
  }, /*#__PURE__*/_react.default.createElement(_use_filters_query.FilterQueryContextProvider, null, children));
};
exports.ChangePointDetectionContextProvider = ChangePointDetectionContextProvider;
function useChangePointDetectionContext() {
  return (0, _react.useContext)(ChangePointDetectionContext);
}
function useRequestParams() {
  return useChangePointDetectionContext().requestParams;
}