/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import CodeMirror from '@skidding/react-codemirror';
import PropTypes from 'prop-types';
import _ from 'lodash';

import { getOptions } from './codeMirror/helpers';

require('codemirror/mode/javascript/javascript');
require('codemirror/lib/codemirror.css');
require('./Editor.css'); // Order Important
require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');
require('codemirror/addon/lint/lint.js');
require('./codeMirror/addon/lint/eslint/eslint-lint.js');
require('codemirror/addon/comment/comment.js');
require('codemirror/addon/comment/continuecomment.js');
require('codemirror/addon/edit/closebrackets.js');
require('codemirror/keymap/sublime.js');

const Editor = ({showLints, onValidCode, onAnyCode, code }) => {
  if (showLints) {
    require('codemirror/addon/lint/lint.css');
  }

  const handleValidCode = (annotationsNotSorted, annotations, cmInstance) => {
    const cleanCode = cmInstance.getValue();
    onValidCode(cleanCode);
  };

  const options = getOptions({}, _.debounce(handleValidCode, 300));

  return (
    <CodeMirror
      value={code}
      onChange={onAnyCode}
      options={options}
    />
  );
};

Editor.propTypes = {
  code: PropTypes.string,
  onValidCode: PropTypes.func,
  onAnyCode: PropTypes.func,
  showLints: PropTypes.bool,
};

Editor.defaultProps = {
  code: '// Your code here:',
  showLints: true,
  onValidCode: (lintedCode) => {},
  onAnyCode: (code) => {},
};

export default Editor;
