"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyzerParameter = void 0;
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _shared_imports = require("../../../shared_imports");
var _lib = require("../../../lib");
var _constants = require("../../../constants");
var _config_context = require("../../../config_context");
var _analyzer_parameter_selects = require("./analyzer_parameter_selects");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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 ANALYZER_OPTIONS = _constants.PARAMETERS_OPTIONS.analyzer;

// token_count requires a value for "analyzer", therefore, we cannot not allow "index_default"
const ANALYZER_OPTIONS_WITHOUT_DEFAULT = _constants.PARAMETERS_OPTIONS.analyzer.filter(({
  value
}) => value !== _constants.INDEX_DEFAULT);
const getCustomAnalyzers = indexSettings => {
  const settings = {}.hasOwnProperty.call(indexSettings, 'index') ? indexSettings.index : indexSettings;
  if (!{}.hasOwnProperty.call(settings, 'analysis') || !{}.hasOwnProperty.call(settings.analysis, 'analyzer')) {
    return undefined;
  }

  // We wrap inside a try catch as the index settings are written in JSON
  // and who knows what the user has entered.
  try {
    return Object.keys(settings.analysis.analyzer).map(value => ({
      value,
      text: value
    }));
  } catch {
    return undefined;
  }
};
const AnalyzerParameter = ({
  path,
  defaultValue,
  label,
  config,
  allowsIndexDefaultOption = true,
  'data-test-subj': dataTestSubj
}) => {
  const {
    value: {
      indexSettings
    }
  } = (0, _config_context.useConfig)();
  const customAnalyzers = getCustomAnalyzers(indexSettings);
  const analyzerOptions = allowsIndexDefaultOption ? ANALYZER_OPTIONS : ANALYZER_OPTIONS_WITHOUT_DEFAULT;
  const fieldOptions = [...analyzerOptions];
  const mapOptionsToSubOptions = {
    language: {
      label: _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.analyzers.languageAnalyzerLabel', {
        defaultMessage: 'Language'
      }),
      options: _constants.PARAMETERS_OPTIONS.languageAnalyzer
    }
  };
  if (customAnalyzers) {
    const customOption = {
      value: 'custom',
      ...(0, _constants.getSuperSelectOption)(_i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.formSelect.analyzer.customTitle', {
        defaultMessage: 'Custom analyzer'
      }), _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.formSelect.analyzer.customDescription', {
        defaultMessage: 'Choose one of your custom analyzers.'
      }))
    };
    fieldOptions.push(customOption);
    mapOptionsToSubOptions.custom = {
      label: _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.analyzers.customAnalyzerLabel', {
        defaultMessage: 'Custom'
      }),
      options: customAnalyzers
    };
  }
  const isDefaultValueInOptions = defaultValue === undefined || fieldOptions.some(option => option.value === defaultValue);
  let mainValue = defaultValue;
  let subValue;
  let isDefaultValueInSubOptions = false;
  if (!isDefaultValueInOptions && mapOptionsToSubOptions !== undefined) {
    // Check if the default value is one of the subOptions
    for (const [key, subOptions] of Object.entries(mapOptionsToSubOptions)) {
      if (subOptions.options.some(option => option.value === defaultValue)) {
        isDefaultValueInSubOptions = true;
        mainValue = key;
        subValue = defaultValue;
        break;
      }
    }
  }
  const [isCustom, setIsCustom] = (0, _react.useState)(!isDefaultValueInOptions && !isDefaultValueInSubOptions);
  const [selectsDefaultValue, setSelectsDefaultValue] = (0, _react.useState)({
    main: mainValue,
    sub: subValue
  });
  const fieldConfig = config ? config : (0, _lib.getFieldConfig)('analyzer');
  const fieldConfigWithLabel = label !== undefined ? {
    ...fieldConfig,
    label
  } : fieldConfig;
  const toggleCustom = field => () => {
    if (isCustom) {
      field.setValue(fieldOptions[0].value);
    } else {
      field.setValue('');
    }
    field.reset({
      resetValue: false
    });
    setSelectsDefaultValue({
      main: undefined,
      sub: undefined
    });
    setIsCustom(!isCustom);
  };
  return /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: path,
    config: fieldConfigWithLabel
  }, field => /*#__PURE__*/_react.default.createElement("div", {
    className: "mappingsEditor__selectWithCustom"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    size: "xs",
    onClick: toggleCustom(field),
    className: "mappingsEditor__selectWithCustom__button",
    "data-test-subj": `${dataTestSubj}-toggleCustomButton`
  }, isCustom ? _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.predefinedButtonLabel', {
    defaultMessage: 'Use built-in analyzer'
  }) : _i18n.i18n.translate('xpack.idxMgmt.mappingsEditor.customButtonLabel', {
    defaultMessage: 'Use custom analyzer'
  })), isCustom ?
  /*#__PURE__*/
  // Wrap inside a flex item to maintain the same padding
  // around the field.
  _react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, null, /*#__PURE__*/_react.default.createElement(_shared_imports.TextField, {
    field: field,
    "data-test-subj": `${dataTestSubj}-custom`
  }))) : /*#__PURE__*/_react.default.createElement(_analyzer_parameter_selects.AnalyzerParameterSelects, {
    onChange: field.setValue,
    mainDefaultValue: selectsDefaultValue.main,
    subDefaultValue: selectsDefaultValue.sub,
    config: fieldConfigWithLabel,
    options: fieldOptions,
    mapOptionsToSubOptions: mapOptionsToSubOptions,
    "data-test-subj": dataTestSubj
  })));
};
exports.AnalyzerParameter = AnalyzerParameter;