"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useJsonStep = void 0;
var _react = require("react");
var _i18n = require("@kbn/i18n");
var _shared_imports = require("../../../../../shared_imports");
/*
 * 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 stringifyJson = json => Object.keys(json).length ? JSON.stringify(json, null, 2) : '{\n\n}';
const useJsonStep = ({
  defaultValue,
  onChange
}) => {
  const [jsonContent, setJsonContent] = (0, _react.useState)(stringifyJson(defaultValue !== null && defaultValue !== void 0 ? defaultValue : {}));
  const [error, setError] = (0, _react.useState)(null);
  const validateContent = (0, _react.useCallback)(() => {
    // We allow empty string as it will be converted to "{}""
    const isValid = jsonContent.trim() === '' ? true : (0, _shared_imports.isJSON)(jsonContent);
    if (!isValid) {
      setError(_i18n.i18n.translate('xpack.idxMgmt.validators.string.invalidJSONError', {
        defaultMessage: 'Invalid JSON format.'
      }));
    } else {
      setError(null);
    }
    return isValid;
  }, [jsonContent]);
  (0, _react.useEffect)(() => {
    const isValid = validateContent();
    const getData = () => {
      const value = isValid && jsonContent.trim() !== '' ? JSON.parse(jsonContent) : {};
      // If no key has been added to the JSON object, we strip it out so an empty object is not sent in the request
      return Object.keys(value).length > 0 ? value : undefined;
    };
    const content = {
      isValid,
      validate: async () => isValid,
      getData
    };
    onChange(content);
  }, [jsonContent, onChange, validateContent]);
  return {
    jsonContent,
    setJsonContent,
    error
  };
};
exports.useJsonStep = useJsonStep;