"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SelectedFieldMappings = exports.MultiFieldMapping = void 0;
var _react = _interopRequireWildcard(require("react"));
var _kea = require("kea");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _index_view_logic = require("../../index_view_logic");
var _ml_inference_logic = require("./ml_inference_logic");
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 TARGET_FIELD_PLACEHOLDER_TEXT_NO_FIELDS = _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetField.placeholder.noFields', {
  defaultMessage: 'Select a source field'
});
const TARGET_FIELD_PLACEHOLDER_TEXT_MULTIPLE_FIELDS = _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetField.placeholder.multipleFields', {
  defaultMessage: 'Automatically created for multi-select'
});
const TARGET_FIELD_PLACEHOLDER_TEXT_TEXT_EXPANSION_MODEL = _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetField.placeholder.textExpansionModel', {
  defaultMessage: 'Automatically created'
});
const TARGET_FIELD_HELP_TEXT_DEFAULT = _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetField.helpText', {
  defaultMessage: 'Optional. Field name where inference results should be saved.'
});
const TARGET_FIELD_HELP_TEXT_TEXT_EXPANSION_MODEL = _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetField.helpTextTextExpansionModel', {
  defaultMessage: 'ELSER target fields are created automatically.'
});
const getInitialTargetFieldPlaceholderText = isTextExpansionModelSelected => isTextExpansionModelSelected ? TARGET_FIELD_PLACEHOLDER_TEXT_TEXT_EXPANSION_MODEL : TARGET_FIELD_PLACEHOLDER_TEXT_NO_FIELDS;
const getTargetFieldHelpText = isTextExpansionModelSelected => isTextExpansionModelSelected ? TARGET_FIELD_HELP_TEXT_TEXT_EXPANSION_MODEL : TARGET_FIELD_HELP_TEXT_DEFAULT;
const MultiFieldMapping = () => {
  var _configuration$fieldM, _configuration$fieldM2;
  const {
    addInferencePipelineModal: {
      configuration,
      selectedSourceFields = []
    },
    isTextExpansionModelSelected,
    sourceFields
  } = (0, _kea.useValues)(_ml_inference_logic.MLInferenceLogic);
  const {
    ingestionMethod
  } = (0, _kea.useValues)(_index_view_logic.IndexViewLogic);
  const {
    addSelectedFieldsToMapping,
    selectFields,
    setTargetField
  } = (0, _kea.useActions)(_ml_inference_logic.MLInferenceLogic);
  const [placeholderText, setPlaceholderText] = (0, _react.useState)(getInitialTargetFieldPlaceholderText(isTextExpansionModelSelected));
  const mappedSourceFields = (_configuration$fieldM = (_configuration$fieldM2 = configuration.fieldMappings) === null || _configuration$fieldM2 === void 0 ? void 0 : _configuration$fieldM2.map(({
    sourceField
  }) => sourceField)) !== null && _configuration$fieldM !== void 0 ? _configuration$fieldM : [];

  // Remove fields that have already been selected or mapped from selectable field options
  const fieldOptions = (sourceFields || []).filter(fieldName => ![...selectedSourceFields, ...mappedSourceFields].includes(fieldName)).map(fieldName => ({
    label: fieldName
  }));
  const selectedFields = selectedSourceFields.map(fieldName => ({
    label: fieldName
  }));
  const targetField = configuration.targetField;
  const isExactlyOneSourceFieldSelected = selectedSourceFields.length === 1;
  const onChangeSelectedFields = selectedFieldNames => {
    selectFields(selectedFieldNames.map(({
      label
    }) => label));
    setTargetField(!isTextExpansionModelSelected && selectedFieldNames.length === 1 ? selectedFieldNames[0].label : '');
    setPlaceholderText(isTextExpansionModelSelected ? TARGET_FIELD_PLACEHOLDER_TEXT_TEXT_EXPANSION_MODEL : selectedFieldNames.length === 0 ? TARGET_FIELD_PLACEHOLDER_TEXT_NO_FIELDS : selectedFieldNames.length === 1 ? selectedFieldNames[0].label : TARGET_FIELD_PLACEHOLDER_TEXT_MULTIPLE_FIELDS);
  };
  const onCreateField = fieldName => {
    const normalizedFieldName = fieldName.trim();
    if (!normalizedFieldName) return;
    selectedFields.push({
      label: normalizedFieldName
    });
    selectFields([...selectedSourceFields, fieldName]);
  };
  const onAddSelectedFields = () => {
    addSelectedFieldsToMapping(isTextExpansionModelSelected);
    setTargetField('');
    setPlaceholderText(getInitialTargetFieldPlaceholderText(isTextExpansionModelSelected));
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 4
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    fullWidth: true,
    label: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.sourceFieldLabel', {
      defaultMessage: 'Source text field'
    }),
    helpText: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.sourceField.helpText', {
      defaultMessage: 'Select an existing field or type in a field name.'
    })
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiComboBox, {
    fullWidth: true,
    "data-telemetry-id": `entSearchContent-${ingestionMethod}-pipelines-configureFields-selectSchemaField`,
    placeholder: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.selectedFields', {
      defaultMessage: 'Selected fields'
    }),
    options: fieldOptions,
    selectedOptions: selectedFields,
    onChange: onChangeSelectedFields,
    onCreateOption: onCreateField
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false,
    style: {
      paddingTop: '32px'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
    type: "sortRight"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: 4
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    label: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.targetFieldLabel', {
      defaultMessage: 'Target field'
    }),
    helpText: getTargetFieldHelpText(isTextExpansionModelSelected),
    fullWidth: true
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
    prepend: "ml.inference.",
    onChange: e => setTargetField(e.target.value),
    "data-telemetry-id": `entSearchContent-${ingestionMethod}-pipelines-configureFields-targetField`,
    disabled: isTextExpansionModelSelected || !isExactlyOneSourceFieldSelected,
    value: targetField,
    placeholder: placeholderText,
    fullWidth: true
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    style: {
      paddingTop: '20px'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    color: "primary",
    "data-telemetry-id": `entSearchContent-${ingestionMethod}-pipelines-configureFields-addSelectedFieldsToMapping`,
    disabled: selectedFields.length === 0,
    iconType: "plusInCircle",
    onClick: onAddSelectedFields,
    style: {
      width: '60px'
    }
  }, _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.addMapping', {
    defaultMessage: 'Add'
  })))));
};
exports.MultiFieldMapping = MultiFieldMapping;
const SelectedFieldMappings = ({
  isReadOnly
}) => {
  var _configuration$fieldM3;
  const {
    removeFieldFromMapping
  } = (0, _kea.useActions)(_ml_inference_logic.MLInferenceLogic);
  const {
    addInferencePipelineModal: {
      configuration
    }
  } = (0, _kea.useValues)(_ml_inference_logic.MLInferenceLogic);
  const columns = [{
    'data-test-subj': 'sourceFieldCell',
    field: 'sourceField',
    name: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.fieldMappings.sourceFieldHeader', {
      defaultMessage: 'Source text field'
    })
  }, {
    align: 'left',
    name: '',
    render: () => /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      type: "sortRight"
    }),
    width: '60px'
  }, {
    align: 'right',
    field: 'targetField',
    name: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.fieldMappings.targetFieldHeader', {
      defaultMessage: 'Target field'
    })
  },
  // Do not add action column in read-only mode
  ...(isReadOnly ? [] : [{
    actions: [{
      color: 'danger',
      description: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.actions.deleteMapping', {
        defaultMessage: 'Delete this mapping'
      }),
      icon: 'trash',
      isPrimary: true,
      name: fieldMapping => _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.actions.deleteMapping.caption', {
        defaultMessage: `Delete mapping '{sourceField}' - '{targetField}'`,
        values: {
          sourceField: fieldMapping.sourceField,
          targetField: fieldMapping.targetField
        }
      }),
      onClick: fieldMapping => removeFieldFromMapping(fieldMapping.sourceField),
      type: 'icon'
    }],
    name: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.actions', {
      defaultMessage: 'Actions'
    }),
    width: '10%'
  }])];
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiBasicTable, {
    columns: columns,
    items: (_configuration$fieldM3 = configuration.fieldMappings) !== null && _configuration$fieldM3 !== void 0 ? _configuration$fieldM3 : [],
    rowHeader: "sourceField",
    tableCaption: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.fieldMappings.tableCaption', {
      defaultMessage: 'Field mappings'
    }),
    noItemsMessage: _i18n.i18n.translate('xpack.enterpriseSearch.content.indices.pipelines.addInferencePipelineModal.steps.fields.fieldMappings.noFieldMappings', {
      defaultMessage: 'No field mappings selected'
    })
  }));
};
exports.SelectedFieldMappings = SelectedFieldMappings;