"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.configurationFormSchema = exports.ConfigurationStep = void 0;
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _eui = require("@elastic/eui");
var _shared_imports = require("../../../../shared_imports");
var _app_context = require("../../../app_context");
var _indices_selector = require("./fields/indices_selector");
var _documentation = require("../../../services/documentation");
var _create_policy_context = require("../create_policy_context");
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 configurationFormSchema = {
  name: {
    type: _shared_imports.FIELD_TYPES.TEXT,
    label: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.policyNameField', {
      defaultMessage: 'Policy name'
    }),
    validations: [{
      validator: _shared_imports.fieldValidators.emptyField(_i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.policyNameRequiredError', {
        defaultMessage: 'A policy name value is required.'
      }))
    }]
  },
  type: {
    type: _shared_imports.FIELD_TYPES.SELECT,
    label: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.policyTypeLabel', {
      defaultMessage: 'Policy type'
    }),
    validations: [{
      validator: _shared_imports.fieldValidators.emptyField(_i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.typeRequiredError', {
        defaultMessage: 'A policy type value is required.'
      }))
    }]
  },
  sourceIndices: {
    label: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.sourceIndicesLabel', {
      defaultMessage: 'Source indices'
    }),
    validations: [{
      validator: _shared_imports.fieldValidators.emptyField(_i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.sourceIndicesRequiredError', {
        defaultMessage: 'At least one source index is required.'
      }))
    }]
  },
  query: {
    type: _shared_imports.FIELD_TYPES.JSON,
    label: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.queryLabel', {
      defaultMessage: 'Query (optional)'
    }),
    serializer: jsonString => {
      let parsedJSON;
      try {
        parsedJSON = JSON.parse(jsonString);
      } catch {
        parsedJSON = {};
      }
      return parsedJSON;
    },
    deserializer: json => json && typeof json === 'object' ? JSON.stringify(json, null, 2) : '{\n\n}',
    validations: [{
      validator: _shared_imports.fieldValidators.isJsonField(_i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.queryInvalidError', {
        defaultMessage: 'The query is not valid JSON.'
      }), {
        allowEmptyString: true
      })
    }]
  }
};
exports.configurationFormSchema = configurationFormSchema;
const ConfigurationStep = ({
  onNext
}) => {
  const {
    core: {
      application: {
        getUrlForApp
      }
    }
  } = (0, _app_context.useAppContext)();
  const [isPopoverOpen, setIsPopoverOpen] = (0, _react.useState)(false);
  const {
    draft,
    updateDraft,
    updateCompletionState
  } = (0, _create_policy_context.useCreatePolicyContext)();
  const {
    form
  } = (0, _shared_imports.useForm)({
    defaultValue: draft,
    schema: configurationFormSchema,
    id: 'configurationForm'
  });
  const onSubmit = async () => {
    const {
      isValid,
      data
    } = await form.submit();
    if (!isValid) {
      return;
    }

    // Update form completion state
    updateCompletionState(prevCompletionState => ({
      ...prevCompletionState,
      configurationStep: true
    }));

    // Update draft state with the data of the form
    updateDraft(prevDraft => ({
      ...prevDraft,
      ...((0, _lodash.isEmpty)(data.query) ? (0, _lodash.omit)(data, 'query') : data)
    }));

    // And then navigate to the next step
    onNext();
  };
  return /*#__PURE__*/_react.default.createElement(_shared_imports.Form, {
    form: form,
    "data-test-subj": "configurationForm"
  }, /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "name",
    component: _shared_imports.TextField,
    componentProps: {
      fullWidth: false
    },
    "data-test-subj": "policyNameField"
  }), /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "type",
    component: _shared_imports.SelectField,
    labelAppend: /*#__PURE__*/_react.default.createElement(_eui.EuiPopover, {
      button: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
        "data-test-subj": "typePopoverIcon",
        onClick: () => setIsPopoverOpen(isOpen => !isOpen)
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        type: "questionInCircle"
      })),
      isOpen: isPopoverOpen,
      closePopover: () => setIsPopoverOpen(false)
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      size: "s"
    }, /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.typeTitlePopOver",
      defaultMessage: "Determines how to match the data to incoming documents."
    })), /*#__PURE__*/_react.default.createElement("ul", null, /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.matchTypePopOver",
      defaultMessage: "{type} matches an exact value.",
      values: {
        type: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, {
          transparentBackground: true
        }, "Match")
      }
    })), /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.geoMatchTypePopOver",
      defaultMessage: "{type} matches a geographic location.",
      values: {
        type: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, {
          transparentBackground: true
        }, "Geo match")
      }
    })), /*#__PURE__*/_react.default.createElement("li", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.rangeTypePopOver",
      defaultMessage: "{type} matches a number, date, or IP address range.",
      values: {
        type: /*#__PURE__*/_react.default.createElement(_eui.EuiCode, {
          transparentBackground: true
        }, "Range")
      }
    }))))),
    componentProps: {
      fullWidth: false,
      euiFieldProps: {
        'data-test-subj': 'policyTypeField',
        options: [{
          value: 'match',
          text: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.matchOption', {
            defaultMessage: 'Match'
          })
        }, {
          value: 'geo_match',
          text: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.geoMatchOption', {
            defaultMessage: 'Geo match'
          })
        }, {
          value: 'range',
          text: _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.rangeOption', {
            defaultMessage: 'Range'
          })
        }]
      }
    }
  }), /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "sourceIndices",
    component: _indices_selector.IndicesSelector,
    labelAppend: /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      size: "xs"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
      target: "_blank",
      "data-test-subj": "uploadFileLink",
      href: getUrlForApp('home', {
        path: '#/tutorial_directory/fileDataViz'
      })
    }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.uploadFileLink",
      defaultMessage: "Upload a file"
    }))),
    componentProps: {
      euiFieldProps: {
        'data-test-subj': 'policySourceIndicesField'
      },
      fullWidth: false
    }
  }), /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "query",
    component: _shared_imports.JsonEditorField,
    componentProps: {
      fullWidth: false,
      helpText: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
        id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.queryHelpText",
        defaultMessage: "Defaults to: {code} query.",
        values: {
          code: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
            external: true,
            target: "_blank",
            "data-test-subj": "matchAllQueryLink",
            href: _documentation.documentationService.getMatchAllQueryLink()
          }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
            id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.matchAllLink",
            defaultMessage: "match_all"
          }))
        }
      }),
      codeEditorProps: {
        height: '300px',
        allowFullScreen: true,
        'aria-label': _i18n.i18n.translate('xpack.idxMgmt.enrichPolicyCreate.configurationStep.ariaLabelQuery', {
          defaultMessage: 'Query field data editor'
        }),
        options: {
          lineNumbers: 'off',
          tabSize: 2,
          automaticLayout: true
        }
      }
    }
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    "data-test-subj": "configureStep",
    justifyContent: "spaceBetween",
    style: {
      maxWidth: 400
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    grow: false
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    fill: true,
    color: "primary",
    iconSide: "right",
    iconType: "arrowRight",
    disabled: form.isValid === false,
    "data-test-subj": "nextButton",
    onClick: onSubmit
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.enrichPolicyCreate.configurationStep.nextButtonLabel",
    defaultMessage: "Next"
  })))));
};
exports.ConfigurationStep = ConfigurationStep;