import _extends from "@babel/runtime/helpers/extends";
import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import * as MonacoEditor from 'monaco-editor';
import { useUpdateEffect } from 'ahooks';

var ScriptEditor = function ScriptEditor(_ref) {
  var language = _ref.language,
      prevValue = _ref.prevValue,
      readOnly = _ref.readOnly,
      theme = _ref.theme,
      onChange = _ref.onChange,
      className = _ref.className,
      options = _ref.options;
  var ref = useRef();
  var editorRef = useRef();
  var onChangeSubscribeRef = useRef();

  var init = function init() {
    editorRef.current = MonacoEditor.editor.create(ref.current, _extends({
      value: prevValue,
      language: language,
      contextmenu: false,
      minimap: {
        enabled: false
      },
      readOnly: readOnly,
      theme: theme
    }, options));
    onChangeSubscribeRef.current = editorRef.current.onDidChangeModelContent(function () {
      onChange && onChange(editorRef.current.getValue());
    });
  };

  var destroy = function destroy() {
    if (editorRef.current) {
      //使用完成销毁实例
      editorRef.current.dispose();
      var model = editorRef.current.getModel();

      if (model) {
        model.dispose();
      }
    }

    if (onChangeSubscribeRef.current) {
      debugger;
      onChangeSubscribeRef.current.dispose();
    }
  };

  useEffect(function () {
    init();
    return destroy;
  }, []);
  useUpdateEffect(function () {
    MonacoEditor.editor.setModelLanguage(editorRef.current.getModel(), language);
  }, [language]);
  useUpdateEffect(function () {
    editorRef.current.updateOptions({
      readOnly: readOnly,
      theme: theme
    });
  }, [readOnly, theme]);
  return /*#__PURE__*/React.createElement("div", {
    ref: ref,
    style: {
      height: '100%'
    },
    className: className
  });
};

export default ScriptEditor;
ScriptEditor.propTypes = {
  language: PropTypes.string,
  prevValue: PropTypes.string,
  readOnly: PropTypes.bool,
  theme: PropTypes.string,
  onChange: PropTypes.func,
  className: PropTypes.string,
  options: PropTypes.object
};
ScriptEditor.defaultProps = {
  prevValue: '',
  readOnly: false,
  theme: 'vs'
};