"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.adaptCanvasFilter = adaptCanvasFilter;
var _lodash = require("lodash");
var _types = require("../../types");
/*
 * 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 functionToFilter = {
  timefilter: _types.FilterType.time,
  exactly: _types.FilterType.exactly
};
const defaultFormatter = arg => arg.toString();
const argToValue = (arg, formatter = defaultFormatter) => arg !== null && arg !== void 0 && arg[0] ? formatter(arg[0]) : null;
const convertFunctionToFilterType = func => {
  var _functionToFilter$fun;
  return (_functionToFilter$fun = functionToFilter[func]) !== null && _functionToFilter$fun !== void 0 ? _functionToFilter$fun : _types.FilterType.exactly;
};
const collectArgs = args => {
  const argsKeys = Object.keys(args);
  if (!argsKeys.length) {
    return null;
  }
  return argsKeys.reduce((acc, key) => ({
    ...acc,
    [key]: argToValue(args[key], _lodash.identity)
  }), {});
};
function adaptCanvasFilter(filter) {
  var _argToValue;
  const {
    function: type,
    arguments: args
  } = filter;
  const {
    column,
    filterGroup,
    value: valueArg,
    type: typeArg,
    ...rest
  } = args !== null && args !== void 0 ? args : {};
  return {
    type: convertFunctionToFilterType(type),
    column: argToValue(column),
    filterGroup: argToValue(filterGroup),
    value: (_argToValue = argToValue(valueArg)) !== null && _argToValue !== void 0 ? _argToValue : collectArgs(rest)
  };
}