import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import React, { useState, useEffect } from "react";
import AceEditor from "react-ace";
import Box from "@material-ui/core/Box";
import Button from "@material-ui/core/Button";
import { useToasts } from "../Toasts";
export var RawJSONEditor = function RawJSONEditor(_ref) {
  var content = _ref.content,
      onSave = _ref.onSave;

  var _useState = useState(""),
      _useState2 = _slicedToArray(_useState, 2),
      jsonText = _useState2[0],
      setJSONText = _useState2[1];

  var _useToasts = useToasts(),
      addToast = _useToasts.addToast;

  useEffect(function () {
    if (!content) return;

    if (typeof content === "string") {
      setJSONText(content);
    } else if (typeof content === "object") {
      setJSONText(JSON.stringify(content, null, "  "));
    }
  }, [content]);
  return /*#__PURE__*/React.createElement(Box, {
    position: "relative",
    width: "100%"
  }, /*#__PURE__*/React.createElement(AceEditor, {
    theme: "github",
    mode: "javascript",
    width: "100%",
    value: jsonText,
    editorProps: {
      $blockScrolling: Infinity
    },
    onChange: function onChange(t) {
      return setJSONText(t);
    }
  }), /*#__PURE__*/React.createElement(Box, {
    position: "absolute",
    right: 16,
    top: 16
  }, /*#__PURE__*/React.createElement(Button, {
    variant: "contained",
    color: "primary",
    onClick: function onClick() {
      try {
        onSave(JSON.parse(jsonText));
      } catch (e) {
        addToast("Invalid JSON", "error");
      }
    }
  }, "Save")));
};
export default RawJSONEditor;