var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

/* istanbul ignore file */
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import { Controlled as CodeMirror } from 'react-codemirror2';
import { getMode } from './cm.modes';
import defaults from './cm.options';

import './style.scss';

var CodeEditor = function CodeEditor(_ref) {
  var className = _ref.className,
      _ref$code = _ref.code,
      code = _ref$code === undefined ? '' : _ref$code,
      lang = _ref.lang,
      _ref$options = _ref.options,
      options = _ref$options === undefined ? {} : _ref$options,
      children = _ref.children,
      attr = _objectWithoutProperties(_ref, ['className', 'code', 'lang', 'options', 'children']);

  var _useState = useState(children && typeof children === 'string' ? children : code),
      value = _useState[0],
      setValue = _useState[1];

  var _useState2 = useState(getMode(lang)),
      mode = _useState2[0],
      setMode = _useState2[1];

  useEffect(function () {
    var incValue = children && typeof children === 'string' ? children : code;
    setValue(incValue);
  }, [code, children]);

  useEffect(function () {
    setMode(function (prevMode) {
      var newMode = getMode(lang);
      if (newMode !== prevMode) return newMode;
      return prevMode;
    });
  }, [lang]);

  return React.createElement(
    'div',
    { className: 'CodeEditor ' + (className || '') },
    React.createElement(CodeMirror, _extends({}, attr, {
      onBeforeChange: function onBeforeChange(editor, data, updatedCode) {
        return setValue(updatedCode);
      },
      options: _extends({}, defaults, options, { mode: mode }),
      value: value
    }))
  );
};

CodeEditor.propTypes = process.env.NODE_ENV !== "production" ? {
  className: PropTypes.string,
  /** Code to show in the editor.
   */
  code: PropTypes.string,
  /** CodeMirror language mode to use.
   */
  lang: PropTypes.string,
  /** Custom CodeMirror  configuration.
   */
  options: PropTypes.object,
  /** Syntax highlighting theme.
   */
  theme: PropTypes.oneOf(['light', 'dark'])
} : {};

CodeEditor.defaultProps = {
  options: {},
  theme: 'dark'
};

export default CodeEditor;