"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.timeUnits = exports.EditDataRetentionModal = void 0;
var _react = _interopRequireDefault(require("react"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _i18nReact = require("@kbn/i18n-react");
var _shared_imports = require("../../../../../shared_imports");
var _documentation = require("../../../../services/documentation");
var _common = require("../../../../../../common");
var _app_context = require("../../../../app_context");
var _unit_field = require("./unit_field");
var _api = require("../../../../services/api");
/*
 * 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 timeUnits = [{
  value: 'd',
  text: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.timeUnits.daysLabel', {
    defaultMessage: 'days'
  })
}, {
  value: 'h',
  text: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.timeUnits.hoursLabel', {
    defaultMessage: 'hours'
  })
}, {
  value: 'm',
  text: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.timeUnits.minutesLabel', {
    defaultMessage: 'minutes'
  })
}, {
  value: 's',
  text: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.timeUnits.secondsLabel', {
    defaultMessage: 'seconds'
  })
}];
exports.timeUnits = timeUnits;
const configurationFormSchema = {
  dataRetention: {
    type: _shared_imports.FIELD_TYPES.TEXT,
    label: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.dataRetentionField', {
      defaultMessage: 'Data retention'
    }),
    formatters: [_shared_imports.fieldFormatters.toInt],
    validations: [{
      validator: ({
        value,
        formData
      }) => {
        // If infiniteRetentionPeriod is set, we dont need to validate the data retention field
        if (formData.infiniteRetentionPeriod) {
          return undefined;
        }
        if (!value) {
          return {
            message: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.dataRetentionFieldRequiredError', {
              defaultMessage: 'A data retention value is required.'
            })
          };
        }
        if (value <= 0) {
          return {
            message: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.dataRetentionFieldNonNegativeError', {
              defaultMessage: `A positive value is required.`
            })
          };
        }
      }
    }]
  },
  timeUnit: {
    type: _shared_imports.FIELD_TYPES.TEXT,
    label: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.timeUnitField', {
      defaultMessage: 'Time unit'
    })
  },
  infiniteRetentionPeriod: {
    type: _shared_imports.FIELD_TYPES.TOGGLE,
    defaultValue: false,
    label: _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.infiniteRetentionPeriodField', {
      defaultMessage: 'Keep data indefinitely'
    })
  }
};
const EditDataRetentionModal = ({
  lifecycle,
  dataStreamName,
  onClose
}) => {
  const {
    size,
    unit
  } = (0, _common.splitSizeAndUnits)(lifecycle === null || lifecycle === void 0 ? void 0 : lifecycle.data_retention);
  const {
    services: {
      notificationService
    }
  } = (0, _app_context.useAppContext)();
  const {
    form
  } = (0, _shared_imports.useForm)({
    defaultValue: {
      dataRetention: size,
      timeUnit: unit || 'd',
      // When data retention is not set and lifecycle is enabled, is the only scenario in
      // which data retention will be infinite. If lifecycle isnt set or is not enabled, we
      // dont have inifinite data retention.
      infiniteRetentionPeriod: (lifecycle === null || lifecycle === void 0 ? void 0 : lifecycle.enabled) && !(lifecycle !== null && lifecycle !== void 0 && lifecycle.data_retention)
    },
    schema: configurationFormSchema,
    id: 'editDataRetentionForm'
  });
  const [formData] = (0, _shared_imports.useFormData)({
    form
  });
  const isDirty = (0, _shared_imports.useFormIsModified)({
    form
  });
  const onSubmitForm = async () => {
    const {
      isValid,
      data
    } = await form.submit();
    if (!isValid) {
      return;
    }
    return (0, _api.updateDataRetention)(dataStreamName, data).then(({
      data: responseData,
      error
    }) => {
      if (responseData) {
        const successMessage = _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.successDataRetentionNotification', {
          defaultMessage: 'Data retention updated'
        });
        notificationService.showSuccessToast(successMessage);
        return onClose({
          hasUpdatedDataRetention: true
        });
      }
      if (error) {
        const errorMessage = _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.errorDataRetentionNotification', {
          defaultMessage: "Error updating data retention: '{error}'",
          values: {
            error: error.message
          }
        });
        notificationService.showDangerToast(errorMessage);
      }
      onClose();
    });
  };
  return /*#__PURE__*/_react.default.createElement(_eui.EuiModal, {
    onClose: () => onClose(),
    "data-test-subj": "editDataRetentionModal"
  }, /*#__PURE__*/_react.default.createElement(_shared_imports.Form, {
    form: form,
    "data-test-subj": "editDataRetentionForm"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiModalHeader, null, /*#__PURE__*/_react.default.createElement(_eui.EuiModalHeaderTitle, null, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.modalTitleText",
    defaultMessage: "Edit data retention"
  }), ' ', /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
    color: "hollow"
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
    size: "xs"
  }, _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.techPreviewLabel', {
    defaultMessage: 'Technical preview'
  }))))), /*#__PURE__*/_react.default.createElement(_eui.EuiModalBody, null, /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "dataRetention",
    component: _shared_imports.NumericField,
    labelAppend: /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      size: "xs"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiLink, {
      href: _documentation.documentationService.getUpdateExistingDS(),
      target: "_blank",
      external: true
    }, _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.learnMoreLinkText', {
      defaultMessage: 'How does it work?'
    }))),
    componentProps: {
      fullWidth: false,
      euiFieldProps: {
        disabled: formData.infiniteRetentionPeriod,
        'data-test-subj': `dataRetentionValue`,
        min: 1,
        append: /*#__PURE__*/_react.default.createElement(_unit_field.UnitField, {
          path: "timeUnit",
          options: timeUnits,
          disabled: formData.infiniteRetentionPeriod,
          euiFieldProps: {
            'data-test-subj': 'timeUnit',
            'aria-label': _i18n.i18n.translate('xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.unitsAriaLabel', {
              defaultMessage: 'Time unit'
            })
          }
        })
      }
    }
  }), /*#__PURE__*/_react.default.createElement(_shared_imports.UseField, {
    path: "infiniteRetentionPeriod",
    component: _shared_imports.ToggleField,
    "data-test-subj": "infiniteRetentionPeriod"
  }), /*#__PURE__*/_react.default.createElement(_eui.EuiSpacer, null)), /*#__PURE__*/_react.default.createElement(_eui.EuiModalFooter, null, /*#__PURE__*/_react.default.createElement(_eui.EuiButtonEmpty, {
    "data-test-subj": "cancelButton",
    onClick: () => onClose()
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.cancelButtonLabel",
    defaultMessage: "Cancel"
  })), /*#__PURE__*/_react.default.createElement(_eui.EuiButton, {
    fill: true,
    type: "submit",
    isLoading: false,
    disabled: form.isSubmitted && form.isValid === false || !isDirty,
    "data-test-subj": "saveButton",
    onClick: onSubmitForm
  }, /*#__PURE__*/_react.default.createElement(_i18nReact.FormattedMessage, {
    id: "xpack.idxMgmt.dataStreamsDetailsPanel.editDataRetentionModal.saveButtonLabel",
    defaultMessage: "Save"
  })))));
};
exports.EditDataRetentionModal = EditDataRetentionModal;