"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.TestScript = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _i18n = require("@kbn/i18n");
var _esQuery = require("@kbn/es-query");
var _public = require("@kbn/data-plugin/public");
var _public2 = require("@kbn/kibana-react-plugin/public");
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 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

class TestScript extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "defaultProps", {
      name: 'myScriptedField'
    });
    (0, _defineProperty2.default)(this, "state", {
      isLoading: false,
      additionalFields: [],
      previewData: undefined
    });
    (0, _defineProperty2.default)(this, "previewScript", async searchContext => {
      var _scriptResponse$hits;
      const {
        indexPattern,
        name,
        script,
        executeScript
      } = this.props;
      if (!script || script.length === 0) {
        return;
      }
      this.setState({
        isLoading: true
      });
      let query;
      if (searchContext) {
        const esQueryConfigs = (0, _public.getEsQueryConfig)(this.context.services.uiSettings);
        query = (0, _esQuery.buildEsQuery)(this.props.indexPattern, searchContext.query || [], [], esQueryConfigs);
      }
      const scriptResponse = await executeScript({
        name: name,
        script,
        indexPatternTitle: indexPattern.title,
        query,
        additionalFields: this.state.additionalFields.map(option => option.value),
        http: this.context.services.http
      });
      if (scriptResponse.status !== 200) {
        this.setState({
          isLoading: false,
          previewData: scriptResponse
        });
        return;
      }
      this.setState({
        isLoading: false,
        previewData: (_scriptResponse$hits = scriptResponse.hits) === null || _scriptResponse$hits === void 0 ? void 0 : _scriptResponse$hits.hits.map(hit => ({
          _id: hit._id,
          ...hit._source,
          ...hit.fields
        }))
      });
    });
    (0, _defineProperty2.default)(this, "onAdditionalFieldsChange", selectedOptions => {
      this.setState({
        additionalFields: selectedOptions
      });
    });
  }
  componentDidMount() {
    if (this.props.script) {
      this.previewScript();
    }
  }
  renderPreview(previewData) {
    if (!previewData) {
      return null;
    }
    if (previewData.error) {
      return /*#__PURE__*/_react.default.createElement(_eui.EuiCallOut, {
        title: _i18n.i18n.translate('indexPatternManagement.testScript.errorMessage', {
          defaultMessage: `There's an error in your script`
        }),
        color: "danger",
        iconType: "cross"
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiCodeBlock, {
        language: "json",
        className: "scriptPreviewCodeBlock",
        "data-test-subj": "scriptedFieldPreview"
      }, JSON.stringify(previewData.error, null, ' ')));
    }
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
      size: "xs"
    }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.testScript.resultsLabel",
      defaultMessage: "First 10 results"
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "s"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiCodeBlock, {
      language: "json",
      className: "scriptPreviewCodeBlock",
      "data-test-subj": "scriptedFieldPreview"
    }, JSON.stringify(previewData, null, ' ')));
  }
  renderToolbar() {
    const fieldsByTypeMap = new Map();
    const fields = [];
    this.props.indexPattern.fields.getAll().filter(field => {
      const isMultiField = field.isSubtypeMulti();
      return !field.name.startsWith('_') && !isMultiField && !field.scripted;
    }).forEach(field => {
      if (fieldsByTypeMap.has(field.type)) {
        const fieldsList = fieldsByTypeMap.get(field.type);
        fieldsList.push(field.name);
        fieldsByTypeMap.set(field.type, fieldsList);
      } else {
        fieldsByTypeMap.set(field.type, [field.name]);
      }
    });
    fieldsByTypeMap.forEach((fieldsList, fieldType) => {
      fields.push({
        label: fieldType,
        options: fieldsList.sort().map(fieldName => {
          return {
            value: fieldName,
            label: fieldName
          };
        })
      });
    });
    fields.sort((a, b) => {
      if (a.label < b.label) return -1;
      if (a.label > b.label) return 1;
      return 0;
    });
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      label: _i18n.i18n.translate('indexPatternManagement.testScript.fieldsLabel', {
        defaultMessage: 'Additional fields'
      }),
      fullWidth: true
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiComboBox, {
      placeholder: _i18n.i18n.translate('indexPatternManagement.testScript.fieldsPlaceholder', {
        defaultMessage: 'Select...'
      }),
      options: fields,
      selectedOptions: this.state.additionalFields,
      onChange: selected => this.onAdditionalFieldsChange(selected),
      "data-test-subj": "additionalFieldsSelect",
      fullWidth: true
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "s"
    }), /*#__PURE__*/_react.default.createElement("div", {
      className: "testScript__searchBar"
    }, /*#__PURE__*/_react.default.createElement(this.context.services.unifiedSearch.ui.SearchBar, {
      displayStyle: "inPage",
      appName: 'indexPatternManagement',
      showFilterBar: false,
      showDatePicker: false,
      showQueryInput: true,
      query: this.context.services.data.query.queryString.getDefaultQuery(),
      onQuerySubmit: this.previewScript,
      indexPatterns: [this.props.indexPattern],
      customSubmitButton: /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
        disabled: this.props.script ? false : true,
        isLoading: this.state.isLoading,
        "data-test-subj": "runScriptButton"
      }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "indexPatternManagement.testScript.submitButtonLabel",
        defaultMessage: "Run script"
      }))
    })));
  }
  render() {
    return /*#__PURE__*/_react.default.createElement(_react.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), /*#__PURE__*/_react.default.createElement(_eui.EuiText, null, /*#__PURE__*/_react.default.createElement("h3", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.testScript.resultsTitle",
      defaultMessage: "Preview results"
    })), /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "indexPatternManagement.testScript.instructions",
      defaultMessage: "Run your script to preview the first 10 results. You can also select some additional fields to include in your results to gain more context or add a query to filter on specific documents."
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), this.renderToolbar(), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), this.renderPreview(this.state.previewData));
  }
}
exports.TestScript = TestScript;
(0, _defineProperty2.default)(TestScript, "contextType", _public2.context);