"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SearchService = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _public = require("@kbn/kibana-react-plugin/public");
var _public2 = require("@kbn/kibana-utils-plugin/public");
var _react = _interopRequireDefault(require("react"));
var _rxjs = require("rxjs");
var _search = require("../../common/search");
var _shard_delay = require("../../common/search/aggs/buckets/shard_delay");
var _shard_delay_fn = require("../../common/search/aggs/buckets/shard_delay_fn");
var _aggs = require("./aggs");
var _collectors = require("./collectors");
var _expressions = require("./expressions");
var _warnings = require("./warnings");
var _search_interceptor = require("./search_interceptor");
var _session = require("./session");
var _sessions_mgmt = require("./session/sessions_mgmt");
var _session_indicator = require("./session/session_indicator");
/*
 * 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.
 */

/** @internal */

/** @internal */

class SearchService {
  constructor(initializerContext) {
    (0, _defineProperty2.default)(this, "aggsService", new _aggs.AggsService());
    (0, _defineProperty2.default)(this, "searchSourceService", new _search.SearchSourceService());
    (0, _defineProperty2.default)(this, "searchInterceptor", void 0);
    (0, _defineProperty2.default)(this, "usageCollector", void 0);
    (0, _defineProperty2.default)(this, "sessionService", void 0);
    (0, _defineProperty2.default)(this, "sessionsClient", void 0);
    this.initializerContext = initializerContext;
  }
  setup(core, {
    bfetch,
    expressions,
    usageCollection,
    nowProvider,
    management
  }) {
    const {
      http,
      getStartServices,
      notifications,
      uiSettings,
      executionContext,
      theme
    } = core;
    this.usageCollector = (0, _collectors.createUsageCollector)(getStartServices, usageCollection);
    this.sessionsClient = new _session.SessionsClient({
      http
    });
    this.sessionService = new _session.SessionService(this.initializerContext, getStartServices, this.sessionsClient, nowProvider, this.usageCollector);
    /**
     * A global object that intercepts all searches and provides convenience methods for cancelling
     * all pending search requests, as well as getting the number of pending search requests.
     */
    this.searchInterceptor = new _search_interceptor.SearchInterceptor({
      bfetch,
      toasts: notifications.toasts,
      executionContext,
      http,
      uiSettings,
      startServices: getStartServices(),
      usageCollector: this.usageCollector,
      session: this.sessionService,
      theme,
      searchConfig: this.initializerContext.config.get().search
    });
    expressions.registerFunction((0, _expressions.getEsaggs)({
      getStartServices
    }));
    expressions.registerFunction(_search.kibana);
    expressions.registerFunction(_search.cidrFunction);
    expressions.registerFunction(_search.dateRangeFunction);
    expressions.registerFunction(_search.extendedBoundsFunction);
    expressions.registerFunction(_search.ipRangeFunction);
    expressions.registerFunction(_search.luceneFunction);
    expressions.registerFunction(_search.kqlFunction);
    expressions.registerFunction(_search.kibanaTimerangeFunction);
    expressions.registerFunction(_search.fieldFunction);
    expressions.registerFunction(_search.numericalRangeFunction);
    expressions.registerFunction(_search.geoBoundingBoxFunction);
    expressions.registerFunction(_search.geoPointFunction);
    expressions.registerFunction(_search.rangeFunction);
    expressions.registerFunction(_search.kibanaFilterFunction);
    expressions.registerFunction(_search.existsFilterFunction);
    expressions.registerFunction(_search.queryFilterFunction);
    expressions.registerFunction(_search.rangeFilterFunction);
    expressions.registerFunction(_search.removeFilterFunction);
    expressions.registerFunction(_search.selectFilterFunction);
    expressions.registerFunction(_search.phraseFilterFunction);
    expressions.registerFunction((0, _expressions.getEsdsl)({
      getStartServices
    }));
    expressions.registerFunction((0, _expressions.getEssql)({
      getStartServices
    }));
    expressions.registerFunction((0, _expressions.getEsql)({
      getStartServices
    }));
    expressions.registerFunction((0, _expressions.getEql)({
      getStartServices
    }));
    expressions.registerType(_search.esRawResponse);
    expressions.registerType(_search.eqlRawResponse);
    const aggs = this.aggsService.setup({
      uiSettings,
      registerFunction: expressions.registerFunction,
      nowProvider
    });
    if (this.initializerContext.config.get().search.aggs.shardDelay.enabled) {
      aggs.types.registerBucket(_shard_delay.SHARD_DELAY_AGG_NAME, _shard_delay.getShardDelayBucketAgg);
      expressions.registerFunction(_shard_delay_fn.aggShardDelay);
    }
    const config = this.initializerContext.config.get();
    if (config.search.sessions.enabled) {
      const sessionsConfig = config.search.sessions;
      (0, _sessions_mgmt.registerSearchSessionsMgmt)(core, {
        searchUsageCollector: this.usageCollector,
        sessionsClient: this.sessionsClient,
        management
      }, sessionsConfig, this.initializerContext.env.packageInfo.version);
    }
    return {
      aggs,
      usageCollector: this.usageCollector,
      session: this.sessionService,
      sessionsClient: this.sessionsClient
    };
  }
  start({
    http,
    theme,
    uiSettings,
    chrome,
    application
  }, {
    fieldFormats,
    indexPatterns,
    inspector,
    screenshotMode,
    scriptedFieldsEnabled
  }) {
    const search = (request, options = {}) => {
      return this.searchInterceptor.search(request, options);
    };
    const loadingCount$ = new _rxjs.BehaviorSubject(0);
    http.addLoadingCountSource(loadingCount$);
    const aggs = this.aggsService.start({
      fieldFormats,
      indexPatterns
    });
    const searchSourceDependencies = {
      aggs,
      getConfig: uiSettings.get.bind(uiSettings),
      search,
      onResponse: (request, response, options) => {
        if (!options.disableWarningToasts) {
          const {
            rawResponse
          } = response;
          (0, _warnings.handleWarnings)({
            request: request.body,
            response: rawResponse,
            theme,
            requestId: request.id,
            inspector: options.inspector,
            inspectorService: inspector
          });
        }
        return response;
      },
      scriptedFieldsEnabled
    };
    const config = this.initializerContext.config.get();
    if (config.search.sessions.enabled) {
      chrome.setBreadcrumbsAppendExtension({
        content: (0, _public.toMountPoint)( /*#__PURE__*/_react.default.createElement((0, _session_indicator.createConnectedSearchSessionIndicator)({
          sessionService: this.sessionService,
          application,
          basePath: http.basePath,
          storage: new _public2.Storage(window.localStorage),
          usageCollector: this.usageCollector,
          tourDisabled: screenshotMode.isScreenshotMode()
        })), {
          theme$: theme.theme$
        })
      });
    }
    return {
      aggs,
      search,
      showError: e => {
        this.searchInterceptor.showError(e);
      },
      showWarnings: (adapter, callback) => {
        adapter === null || adapter === void 0 ? void 0 : adapter.getRequests().forEach(request => {
          var _request$response, _request$response$jso;
          const rawResponse = (_request$response = request.response) === null || _request$response === void 0 ? void 0 : (_request$response$jso = _request$response.json) === null || _request$response$jso === void 0 ? void 0 : _request$response$jso.rawResponse;
          if (!rawResponse) {
            return;
          }
          (0, _warnings.handleWarnings)({
            request: request.json,
            response: rawResponse,
            theme,
            callback,
            requestId: request.id,
            inspector: {
              adapter,
              title: request.name,
              id: request.id
            },
            inspectorService: inspector
          });
        });
      },
      session: this.sessionService,
      sessionsClient: this.sessionsClient,
      searchSource: this.searchSourceService.start(indexPatterns, searchSourceDependencies)
    };
  }
  stop() {
    this.aggsService.stop();
    this.searchSourceService.stop();
    this.searchInterceptor.stop();
  }
}
exports.SearchService = SearchService;