"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getStringFieldStatsRequest = exports.fetchStringFieldsStats = void 0;
var _lodash = require("lodash");
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _mlIsPopulatedObject = require("@kbn/ml-is-populated-object");
var _mlErrorUtils = require("@kbn/ml-error-utils");
var _utils = require("./utils");
var _build_random_sampler_agg = require("./build_random_sampler_agg");
var _constants = require("./constants");
var _field_stats = require("../../../../../common/types/field_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 getStringFieldStatsRequest = (params, fields) => {
  const {
    index,
    query,
    runtimeFieldMap
  } = params;
  const size = 0;
  const aggs = {};
  fields.forEach((field, i) => {
    const safeFieldName = field.safeFieldName;
    const top = {
      terms: {
        field: field.fieldName,
        size: 10,
        order: {
          _count: 'desc'
        }
      }
    };
    aggs[`${safeFieldName}_top`] = top;
  });
  const searchBody = {
    query,
    aggs: (0, _build_random_sampler_agg.buildAggregationWithSamplingOption)(aggs, params.samplingOption),
    ...((0, _mlIsPopulatedObject.isPopulatedObject)(runtimeFieldMap) ? {
      runtime_mappings: runtimeFieldMap
    } : {})
  };
  return {
    index,
    size,
    body: searchBody
  };
};
exports.getStringFieldStatsRequest = getStringFieldStatsRequest;
const fetchStringFieldsStats = (dataSearch, params, fields, options) => {
  const {
    samplerShardSize
  } = params;
  const request = getStringFieldStatsRequest(params, fields);
  return dataSearch.search({
    params: request
  }, options).pipe((0, _operators.catchError)(e => (0, _rxjs.of)({
    fields,
    error: (0, _mlErrorUtils.extractErrorProperties)(e)
  })), (0, _operators.map)(resp => {
    if (!(0, _field_stats.isIKibanaSearchResponse)(resp)) return resp;
    const aggregations = resp.rawResponse.aggregations;
    const aggsPath = ['sample'];
    const batchStats = [];
    fields.forEach((field, i) => {
      const safeFieldName = field.safeFieldName;
      const topAggsPath = [...aggsPath, `${safeFieldName}_top`];
      if (samplerShardSize < 1 && field.cardinality >= _constants.SAMPLER_TOP_TERMS_THRESHOLD) {
        topAggsPath.push('top');
      }
      const fieldAgg = (0, _lodash.get)(aggregations, [...topAggsPath], {});
      const {
        topValuesSampleSize,
        topValues
      } = (0, _utils.processTopValues)(fieldAgg, (0, _lodash.get)(aggregations, ['sample', 'doc_count']));
      const stats = {
        fieldName: field.fieldName,
        isTopValuesSampled: true,
        topValues,
        topValuesSampleSize,
        topValuesSamplerShardSize: (0, _lodash.get)(aggregations, ['sample', 'doc_count'])
      };
      batchStats.push(stats);
    });
    return batchStats;
  }));
};
exports.fetchStringFieldsStats = fetchStringFieldsStats;