"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.filtersFunctionFactory = filtersFunctionFactory;
var _interpreter = require("@kbn/interpreter");
var _lodash = require("lodash");
var _services = require("../services");
var _functions = require("../../common/functions");
/*
 * 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.
 */

function getFiltersByGroup(allFilters, groups, ungrouped = false) {
  if (!groups || groups.length === 0) {
    if (!ungrouped) {
      return allFilters;
    }

    // remove all allFilters that belong to a group
    return allFilters.filter(filter => {
      const ast = (0, _interpreter.fromExpression)(filter);
      const expGroups = (0, _lodash.get)(ast, 'chain[0].arguments.filterGroup', []);
      return expGroups.length === 0;
    });
  }
  return allFilters.filter(filter => {
    const ast = (0, _interpreter.fromExpression)(filter);
    const expGroups = (0, _lodash.get)(ast, 'chain[0].arguments.filterGroup', []);
    return expGroups.length > 0 && expGroups.every(expGroup => groups.includes(expGroup));
  });
}
function filtersFunctionFactory(initialize) {
  const fn = (input, {
    group,
    ungrouped
  }) => {
    const {
      expressions,
      filters: filtersService
    } = _services.pluginServices.getServices();
    const filterList = getFiltersByGroup(filtersService.getFilters(), group, ungrouped);
    if (filterList && filterList.length) {
      const filterExpression = filterList.join(' | ');
      const filterAST = (0, _interpreter.fromExpression)(filterExpression);
      const {
        variables
      } = filtersService.getFiltersContext();
      return expressions.interpretAst(filterAST, variables);
    } else {
      const filterType = initialize.types.filter;
      return filterType === null || filterType === void 0 ? void 0 : filterType.from(null, {});
    }
  };
  return (0, _functions.buildFiltersFunction)(fn);
}