import React, { Component } from "react";
import { UnControlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/addon/selection/active-line.js';
import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/mode/clike/clike';
import 'codemirror/mode/css/css';

import UserSubmitComponent from "./UserSubmitComponent";

import "./index.css";
import "./editor.css";

class m_editor extends Component {
  constructor(props) {
    super(props);
    this.editorDidMount = this.editorDidMount.bind(this)
    this.state = {
      editorValue: this.props.content,
      changeValue: this.props.content,
      prevHeight: 0
    };
  }
  componentDidUpdate = (prevProps) => {
    if (prevProps && this.props && this.props.content !== prevProps.content) {
      this.setState({
        editorValue: this.props.content
      })
    }
  }
  changeEditor = (editorValue, data) => {
    this.setState({
      changeValue: editorValue.getValue(),
    });
  };
  editorDidMount = (cm, data) => {
    if (this.props.goLine)
      cm.scrollIntoView({ line: this.props.goLine, char: 1 }, 200)
  };
  render() {
    const { editorValue, changeValue } = this.state;
    const { readOnly, editorType, currentBranch, descName, checkName } = this.props;
    const editor_options = {
      lineNumbers: "on",
      lineWrapping: true, //强制换行
      selectOnLineNumbers: true,
      lineHeight: 24,
      renderLineHighlight: "line",
      revealHorizontalRightPadding: 5,
      placeholder: "请输入内容",
      readOnly: readOnly,
      cursorStyle: readOnly ? "underline-thin" : "line",
      folding: true,
      foldingStrategy: "indentation", // 代码可分小段折叠
      automaticLayout: true, // 自适应布局
      overviewRulerBorder: false, // 不要滚动条的边框
      scrollBeyondLastLine: false, // 取消代码后面一大段空白
      styleActiveLine: true,//光标代码高亮
      minimap: {
        // 不要小地图
        enabled: false,
      },
    };
    return (
      <React.Fragment>
        <div className="editorBorderBox">
          <CodeMirror
            placeholder="请输入内容"
            value={editorValue}
            options={editor_options}
            onChange={this.changeEditor}
            onUpdate={this.editorDidMount}
          />
        </div>
        {!readOnly && (
          <div className="editorBorderSubmitBox" style={{ padding: "20px" }}>
            <UserSubmitComponent
              {...this.props}
              {...this.state}
              filepath={`${this.props.filepath}`}
              content={changeValue}
              editor_type={editorType}
              currentBranch={currentBranch}
              descName={descName}
              checkName={checkName}
            ></UserSubmitComponent>
          </div>
        )}
      </React.Fragment>
    );
  }
}
export default m_editor;
