"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.truthy = exports.createFiltersFromMultiValueClickAction = void 0;
var _esQuery = require("@kbn/es-query");
var _lodash = require("lodash");
var _create_filters_from_value_click = require("./create_filters_from_value_click");
var _query = require("../../query");
/*
 * 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.
 */

const truthy = value => !!value;

/** @public */
exports.truthy = truthy;
const createFiltersFromMultiValueClickAction = async ({
  data,
  negate
}) => {
  if (!data || data.length === 0) return;
  const result = (await Promise.all(data.map(async d => {
    var _table$meta;
    const {
      table,
      cells,
      relation
    } = d;
    const dataViewId = table === null || table === void 0 ? void 0 : (_table$meta = table.meta) === null || _table$meta === void 0 ? void 0 : _table$meta.source;
    if (!dataViewId) return;
    const filters = (await Promise.all(cells.map(async ({
      column,
      row
    }) => await (0, _create_filters_from_value_click.createFilter)(table, column, row)))).flat().filter(truthy);
    const uniqueFilters = (0, _lodash.uniqWith)((0, _query.mapAndFlattenFilters)(filters), (a, b) => (0, _esQuery.compareFilters)(a, b, _esQuery.COMPARE_ALL_OPTIONS));
    if (uniqueFilters.length === 0) return;
    if (uniqueFilters.length === 1) {
      return negate ? [(0, _esQuery.toggleFilterNegated)(uniqueFilters[0])] : uniqueFilters;
    }
    if (!relation) {
      return negate ? uniqueFilters.map(f => (0, _esQuery.toggleFilterNegated)(f)) : uniqueFilters;
    }
    const filtersHaveAlias = uniqueFilters.every(f => f.meta.alias);
    const alias = filtersHaveAlias ? uniqueFilters.map(f => f.meta.alias).join(` ${relation} `) : '';
    return (0, _esQuery.buildCombinedFilter)(relation, uniqueFilters, {
      id: dataViewId
    }, undefined, negate, alias);
  }))).flat().filter(truthy);
  if (result.length === 0) return;
  return result;
};
exports.createFiltersFromMultiValueClickAction = createFiltersFromMultiValueClickAction;