"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.syncFilterExpression = syncFilterExpression;
var _interpreter = require("@kbn/interpreter");
var _objectPathImmutable = _interopRequireDefault(require("object-path-immutable"));
var _lodash = require("lodash");
/*
 * 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 {
  set,
  del
} = _objectPathImmutable.default;
function syncFilterExpression(config, filterExpression, fields = []) {
  let changed = false;
  const filterAst = (0, _interpreter.fromExpression)(filterExpression);
  const newAst = fields.reduce((ast, field) => {
    const val = (0, _lodash.get)(ast, `chain[0].arguments.${field}[0]`);
    if (val !== config[field]) {
      changed = true;
      if (!config[field]) {
        // remove value if not in expression
        return del(ast, `chain.0.arguments.${field}`);
      }
      return set(ast, `chain.0.arguments.${field}.0`, config[field]);
    }
    return ast;
  }, filterAst);
  return {
    changed,
    newAst
  };
}