"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getSortForSearchSource = getSortForSearchSource;
var _get_sort = require("./get_sort");
var _get_es_query_sort = require("./get_es_query_sort");
/*
 * 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.
 */

/**
 * Prepares sort for search source, that's sending the request to ES
 * - Adds default sort if necessary
 * - Handles the special case when there's sorting by date_nanos typed fields
 *   the addon of the numeric_type guarantees the right sort order
 *   when there are indices with date and indices with date_nanos field
 */
function getSortForSearchSource({
  sort,
  dataView,
  defaultSortDir,
  includeTieBreaker = false
}) {
  const defaultDirection = defaultSortDir || 'desc';
  if (!sort || !dataView || Array.isArray(sort) && sort.length === 0) {
    if (dataView !== null && dataView !== void 0 && dataView.timeFieldName) {
      // sorting by index order
      return [{
        _doc: defaultDirection
      }];
    } else {
      return [{
        _score: defaultDirection
      }];
    }
  }
  const {
    timeFieldName
  } = dataView;
  const sortPairs = (0, _get_sort.getSort)(sort, dataView);
  const sortForSearchSource = sortPairs.map(sortPair => {
    if (timeFieldName && sortPair[timeFieldName]) {
      return (0, _get_es_query_sort.getESQuerySortForTimeField)({
        sortDir: sortPair[timeFieldName],
        timeFieldName,
        isTimeNanosBased: dataView.isTimeNanosBased()
      });
    }
    return sortPair;
  });

  // This tie breaker is skipped for CSV reports as it uses PIT
  if (includeTieBreaker && timeFieldName && sortPairs.length) {
    const firstSortPair = sortPairs[0];
    const firstPairSortDir = Array.isArray(firstSortPair) ? firstSortPair[1] : Object.values(firstSortPair)[0];
    sortForSearchSource.push((0, _get_es_query_sort.getESQuerySortForTieBreaker)({
      sortDir: firstPairSortDir,
      tieBreakerFieldName: _get_es_query_sort.DEFAULT_TIE_BREAKER_NAME
    }));
  }
  return sortForSearchSource;
}