import React, { useState, useCallback, useRef } from "react";
import { Row, Col, CodeEditor, Button } from "@tencent/tea-component";

export default function CodeEditorExample() {
  const editorRef = useRef(null);
  const [ready, setReady] = useState(false);
  const [editorValue, setEditorValue] = useState("");

  // onReady 的时候可以拿到编辑器实例引用，可以用 Ref 保存起来
  const onReady = useCallback(instance => {
    editorRef.current = instance;
    setReady(true);
  }, []);

  // onEdit 的时候也可以拿到实例
  const onEdit = useCallback(instance => {
    // getValue() 是个异步方法，返回 Promise
    instance.getValue().then(value => setEditorValue(value));
  }, []);

  // 设置编辑器当前内容
  const setExampleCode = useCallback(() => {
    if (editorRef.current) {
      const exampleCode = `console.log('hello <CodeEditor />');`;
      editorRef.current.setValue(exampleCode);
      editorRef.current.updateOptions({ readOnly: true });
      editorRef.current.focus();
      setEditorValue(exampleCode);
    }
  }, []);

  return (
    <>
      <section style={{ border: "1px solid #ddd" }}>
        <Row gap={10}>
          <Col>
            <CodeEditor
              style={{ height: 400 }}
              options={{ language: "javascript" }}
              onReady={onReady}
              onEdit={onEdit}
              autoFocus
            />
          </Col>
          <Col style={{ borderLeft: "1px solid #ddd" }}>
            <pre style={{ height: 400, overflow: "auto" }}>{editorValue}</pre>
          </Col>
        </Row>
      </section>
      <Button disabled={!ready} onClick={setExampleCode}>
        加载示例代码
      </Button>
    </>
  );
}
