"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.OutputFormKafkaTopics = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _eui = require("@elastic/eui");
var _i18nReact = require("@kbn/i18n-react");
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _styledComponents = _interopRequireWildcard(require("styled-components"));
var _hooks = require("../../../../../../hooks");
var _constants = require("../../../../../../../common/constants");
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 OutputFormKafkaTopics = props => {
  const {
    inputs
  } = props;
  const {
    props: {
      onChange,
      id
    },
    value: topics,
    formRowProps: {
      error: errors
    }
  } = inputs.kafkaTopicsInput;
  const theme = (0, _styledComponents.useTheme)();
  const [autoFocus, setAutoFocus] = (0, _react.useState)(false);
  const {
    docLinks
  } = (0, _hooks.useStartServices)();
  const indexedErrors = (0, _react.useMemo)(() => {
    if (!errors) {
      return [];
    }
    return errors.reduce((acc, err) => {
      if (err.index === undefined) {
        return acc;
      }
      if (!acc[err.index]) {
        acc[err.index] = [];
      }
      if (!err.condition) {
        acc[err.index].push(err.message);
      }
      return acc;
    }, []);
  }, [errors]);
  const indexedConditionErrors = (0, _react.useMemo)(() => {
    if (!errors) {
      return [];
    }
    return errors.reduce((acc, err) => {
      if (err.index === undefined) {
        return acc;
      }
      if (!acc[err.index]) {
        acc[err.index] = [];
      }
      if (err.condition) {
        acc[err.index].push(err.message);
      }
      return acc;
    }, []);
  }, [errors]);
  const handleTopicProcessorChange = (0, _react.useCallback)((index, field, value) => {
    const updatedTopics = topics.map((topic, i) => {
      if (i === index) {
        if (field === 'topic') {
          return {
            ...topic,
            topic: value
          };
        } else {
          return {
            ...topic,
            when: {
              ...(topic.when || {}),
              ...(field === 'condition' ? {
                condition: value
              } : {}),
              ...(field === 'type' ? {
                type: value
              } : {})
            }
          };
        }
      }
      return topic;
    });
    onChange(updatedTopics);
  }, [topics, onChange]);
  const addTopicProcessor = (0, _react.useCallback)(() => {
    setAutoFocus(true);
    const updatedTopics = [...topics, {
      topic: '',
      when: {
        type: _constants.kafkaTopicWhenType.Contains
      }
    }];
    onChange(updatedTopics);
  }, [topics, onChange]);
  const deleteTopicProcessor = (0, _react.useCallback)(index => {
    const updatedTopics = topics.filter((_, i) => i !== index);
    indexedErrors.splice(index, 1);
    indexedConditionErrors.splice(index, 1);
    onChange(updatedTopics);
  }, [topics, indexedErrors, indexedConditionErrors, onChange]);
  const displayErrors = errorMessages => {
    return errorMessages !== null && errorMessages !== void 0 && errorMessages.length ? errorMessages.map((item, idx) => /*#__PURE__*/_react.default.createElement(_eui.EuiFormErrorText, {
      key: idx
    }, item)) : null;
  };
  const globalErrors = (0, _react.useMemo)(() => {
    return errors && errors.filter(err => err.index === undefined).map(({
      message
    }) => message);
  }, [errors]);
  const kafkaTopicWhenTypes = (0, _react.useMemo)(() => Object.keys(_constants.kafkaTopicWhenType).map(type => ({
    text: _constants.kafkaTopicWhenType[type],
    label: type
  })), []);
  const DraggableDiv = _styledComponents.default.div`
    margin: ${styledProps => styledProps.theme.eui.euiSizeS};
  `;
  const onDragEndHandler = (0, _react.useCallback)(({
    source,
    destination
  }) => {
    if (source && destination) {
      const items = (0, _eui.euiDragDropReorder)(topics, source.index, destination.index);
      const sourceErrors = indexedErrors[source.index];
      indexedErrors.splice(source.index, 1);
      indexedErrors.splice(destination.index, 0, sourceErrors);
      const sourceConditionErrors = indexedConditionErrors[source.index];
      indexedConditionErrors.splice(source.index, 1);
      indexedConditionErrors.splice(destination.index, 0, sourceConditionErrors);
      onChange(items);
    }
  }, [topics, indexedErrors, indexedConditionErrors, onChange]);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiPanel, {
    borderRadius: "m",
    hasShadow: false,
    paddingSize: 'm',
    color: 'subdued',
    "data-test-subj": "settingsOutputsFlyout.kafkaTopicsPanel"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiTitle, {
    size: "s"
  }, /*#__PURE__*/_react.default.createElement("h3", {
    id: "FleetEditOutputFlyoutKafkaHeaders"
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.settings.editOutputFlyout.kafkaTopcisTitle",
    defaultMessage: "Topics"
  }))), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, (0, _extends2.default)({
    fullWidth: true,
    label: /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.settings.editOutputFlyout.kafkaTopicsDefaultTopicLabel",
      defaultMessage: "Default topic"
    })
  }, inputs.kafkaDefaultTopicInput.formRowProps), /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, (0, _extends2.default)({
    "data-test-subj": "settingsOutputsFlyout.kafkaDefaultTopicInput",
    fullWidth: true
  }, inputs.kafkaDefaultTopicInput.props))), topics.length > 0 && /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
    fullWidth: true,
    label: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.settings.editOutputFlyout.kafkaTopicsProcessorsLabel",
      defaultMessage: "Processors"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      color: "subdued",
      size: "xs"
    }, /*#__PURE__*/_react.default.createElement("i", null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
      id: "xpack.fleet.settings.editOutputFlyout.kafkaTopicsProcessorsHelpText",
      defaultMessage: "For more information read the {link}.",
      values: {
        link: /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
          href: docLinks.links.fleet.kafkaSettings,
          target: '_blank'
        }, "documentation")
      }
    }))))
  }, topics.length > 1 ? /*#__PURE__*/_react.default.createElement(_eui.EuiDragDropContext, {
    onDragEnd: onDragEndHandler
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiDroppable, {
    droppableId: `${id}Droppable`,
    spacing: "none"
  }, topics.map((topic, index) => {
    const topicErrors = indexedErrors[index];
    const topicConditionErrors = indexedConditionErrors[index];
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, {
      key: index
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiDraggable, {
      spacing: "m",
      index: index,
      draggableId: `${id}${index}Draggable`,
      customDragHandle: true,
      style: {
        paddingLeft: 0,
        paddingRight: 0
      }
    }, (provided, state) => {
      var _topic$when, _topicConditionErrors, _topic$when2, _topicConditionErrors2, _topicErrors$length, _topicErrors$length2;
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
        size: "s"
      }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
        gutterSize: "none",
        wrap: true,
        style: state.isDragging ? {
          background: theme.eui.euiPanelBackgroundColorModifiers.plain
        } : {}
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false
      }, /*#__PURE__*/_react.default.createElement(DraggableDiv, (0, _extends2.default)({
        "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorDragHandle${index}`
      }, provided.dragHandleProps, {
        "aria-label": _i18n.i18n.translate('xpack.fleet.settings.sortHandle', {
          defaultMessage: 'Sort host handle'
        })
      }), /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
        color: "text",
        type: "grab"
      }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        style: {
          flex: '30%',
          paddingRight: 10
        }
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
        fullWidth: true
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, {
        "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorWhenInput${index}`,
        fullWidth: true,
        options: kafkaTopicWhenTypes,
        value: (_topic$when = topic.when) === null || _topic$when === void 0 ? void 0 : _topic$when.type,
        onChange: e => handleTopicProcessorChange(index, 'type', e.target.value)
      }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        style: {
          flex: '40%'
        }
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
        fullWidth: true,
        error: displayErrors(topicConditionErrors),
        isInvalid: ((_topicConditionErrors = topicConditionErrors === null || topicConditionErrors === void 0 ? void 0 : topicConditionErrors.length) !== null && _topicConditionErrors !== void 0 ? _topicConditionErrors : 0) > 0
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
        "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorConditionInput${index}`,
        value: (_topic$when2 = topic.when) === null || _topic$when2 === void 0 ? void 0 : _topic$when2.condition,
        isInvalid: ((_topicConditionErrors2 = topicConditionErrors === null || topicConditionErrors === void 0 ? void 0 : topicConditionErrors.length) !== null && _topicConditionErrors2 !== void 0 ? _topicConditionErrors2 : 0) > 0,
        onChange: e => handleTopicProcessorChange(index, 'condition', e.target.value)
      }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        grow: false,
        style: {
          marginTop: 10
        }
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
        "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorDeleteButton${index}`,
        color: "text",
        onClick: () => deleteTopicProcessor(index),
        iconType: "cross",
        "aria-label": _i18n.i18n.translate('xpack.fleet.multiRowInput.deleteButton', {
          defaultMessage: 'Delete row'
        })
      })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
        style: {
          flex: '0 50%',
          marginLeft: 'auto',
          marginRight: 23,
          paddingTop: 10
        }
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
        fullWidth: true,
        error: displayErrors(topicErrors),
        isInvalid: ((_topicErrors$length = topicErrors === null || topicErrors === void 0 ? void 0 : topicErrors.length) !== null && _topicErrors$length !== void 0 ? _topicErrors$length : 0) > 0
      }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
        "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorTopicInput${index}`,
        autoFocus: autoFocus,
        prepend: "Topic",
        value: topic.topic,
        isInvalid: ((_topicErrors$length2 = topicErrors === null || topicErrors === void 0 ? void 0 : topicErrors.length) !== null && _topicErrors$length2 !== void 0 ? _topicErrors$length2 : 0) > 0,
        onChange: e => handleTopicProcessorChange(index, 'topic', e.target.value)
      })))));
    }));
  }))) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, topics.map((topic, index) => {
    var _topic$when3, _topicConditionErrors3, _topic$when4, _topicConditionErrors4, _topicErrors$length3, _topicErrors$length4;
    const topicErrors = indexedErrors[index];
    const topicConditionErrors = indexedConditionErrors[index];
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
      size: "s"
    }), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      gutterSize: "none",
      wrap: true
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      style: {
        flex: '30%',
        paddingRight: 10
      }
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      fullWidth: true
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiSelect, {
      "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorWhenInput${index}`,
      fullWidth: true,
      options: kafkaTopicWhenTypes,
      value: (_topic$when3 = topic.when) === null || _topic$when3 === void 0 ? void 0 : _topic$when3.type,
      onChange: e => handleTopicProcessorChange(index, 'type', e.target.value)
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      style: {
        flex: '40%'
      }
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      fullWidth: true,
      error: displayErrors(topicConditionErrors),
      isInvalid: ((_topicConditionErrors3 = topicConditionErrors === null || topicConditionErrors === void 0 ? void 0 : topicConditionErrors.length) !== null && _topicConditionErrors3 !== void 0 ? _topicConditionErrors3 : 0) > 0
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
      "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorConditionInput${index}`,
      value: (_topic$when4 = topic.when) === null || _topic$when4 === void 0 ? void 0 : _topic$when4.condition,
      isInvalid: ((_topicConditionErrors4 = topicConditionErrors === null || topicConditionErrors === void 0 ? void 0 : topicConditionErrors.length) !== null && _topicConditionErrors4 !== void 0 ? _topicConditionErrors4 : 0) > 0,
      onChange: e => handleTopicProcessorChange(index, 'condition', e.target.value)
    }))), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      grow: false,
      style: {
        marginTop: 10
      }
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonIcon, {
      "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorDeleteButton${index}`,
      color: "text",
      onClick: () => deleteTopicProcessor(index),
      iconType: "cross",
      "aria-label": _i18n.i18n.translate('xpack.fleet.multiRowInput.deleteButton', {
        defaultMessage: 'Delete row'
      })
    })), /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
      style: {
        flex: '0 53%',
        marginLeft: 'auto',
        marginRight: 23,
        paddingTop: 10
      }
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFormRow, {
      fullWidth: true,
      error: displayErrors(topicErrors),
      isInvalid: ((_topicErrors$length3 = topicErrors === null || topicErrors === void 0 ? void 0 : topicErrors.length) !== null && _topicErrors$length3 !== void 0 ? _topicErrors$length3 : 0) > 0
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiFieldText, {
      "data-test-subj": `settingsOutputsFlyout.kafkaTopicsProcessorTopicInput${index}`,
      isInvalid: ((_topicErrors$length4 = topicErrors === null || topicErrors === void 0 ? void 0 : topicErrors.length) !== null && _topicErrors$length4 !== void 0 ? _topicErrors$length4 : 0) > 0,
      autoFocus: autoFocus,
      prepend: "Topic",
      value: topic.topic,
      onChange: e => handleTopicProcessorChange(index, 'topic', e.target.value)
    })))));
  }))), displayErrors(globalErrors), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    "data-test-subj": "fleetServerHosts.kafkaTopicsInput.addRowButton",
    size: "xs",
    flush: "left",
    iconType: "plusInCircle",
    onClick: addTopicProcessor
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.fleet.kafkaTopics.addTopicProcessor",
    defaultMessage: "Add topic processor"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, {
    size: "m"
  }));
};
exports.OutputFormKafkaTopics = OutputFormKafkaTopics;