"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useJson = void 0;
var _react = require("react");
var _i18n = require("@kbn/i18n");
var _string = require("../../../static/validators/string");
/*
 * 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.
 */

const stringifyJson = json => Object.keys(json).length ? JSON.stringify(json, null, 2) : '{\n\n}';
const useJson = ({
  defaultValue = {},
  onUpdate,
  value
}) => {
  const isControlled = value !== undefined;
  const isMounted = (0, _react.useRef)(false);
  const [content, setContent] = (0, _react.useState)(isControlled ? value : stringifyJson(defaultValue));
  const [error, setError] = (0, _react.useState)(null);
  const validate = (0, _react.useCallback)(() => {
    // We allow empty string as it will be converted to "{}""
    const isValid = content.trim() === '' ? true : (0, _string.isJSON)(content);
    if (!isValid) {
      setError(_i18n.i18n.translate('esUi.validation.string.invalidJSONError', {
        defaultMessage: 'Invalid JSON'
      }));
    } else {
      setError(null);
    }
    return isValid;
  }, [content]);
  const formatContent = (0, _react.useCallback)(() => {
    const isValid = validate();
    const data = isValid && content.trim() !== '' ? JSON.parse(content) : {};
    return data;
  }, [validate, content]);
  (0, _react.useEffect)(() => {
    if (!isMounted.current || isControlled) {
      return;
    }
    const isValid = validate();
    onUpdate({
      data: {
        raw: content,
        format: formatContent
      },
      validate,
      isValid
    });
  }, [onUpdate, content, formatContent, validate, isControlled]);
  (0, _react.useEffect)(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);
  return {
    content,
    setContent,
    error,
    isControlled
  };
};
exports.useJson = useJson;