// @flow

import React from "react";
import Loadable from "react-loadable";

class GraphQLExplorerConsoleResultsViewer extends React.PureComponent {
  componentDidMount() {
    const { CodeMirror } = this.props;

    this.resultsCodeMirror = CodeMirror(this.resultsElement, {
      value: "",
      theme: "graphql",
      mode: "graphql-results",
      readOnly: true
    });
  }

  componentWillUnmount() {
    if (this.resultsCodeMirror) {
      this.resultsCodeMirror = null;
    }
  }

  render() {
    return (
      <div ref={(el) => this.resultsElement = el} />
    );
  }
}

// Instead of exporting the viewer directly, we'll export a `Loadable`
// Component that will allow us to load in dependencies and render the editor
// until then.
export default Loadable.Map({
  loader: {
    CodeMirror: () => (
      import('./codemirror').then((module) => (
        // Add a "zero" delay after the module has loaded, to allow their
        // styles to take effect.
        new Promise((resolve) => {
          setTimeout(() => resolve(module.default), 0);
        })
      ))
    )
  },

  loading(props) {
    if (props.error) {
      return (
        <div>{props.error}</div>
      );
    } else if (props.pastDelay) {
      return (
        <div>Loading...</div>
      );
    } else {
      return null;
    }
  },

  render(loaded, props) {
    return (
      <GraphQLExplorerConsoleResultsViewer CodeMirror={loaded.CodeMirror} />
    );
  }
});

@@ -174,16 +174,20 @@
     
-const %7B 
+this.results
 Code
@@ -192,18 +192,16 @@
 deMirror
- %7D
  = this.
@@ -209,40 +209,9 @@
 rops
-;%0A%0A    this.resultsCodeMirror = 
+.
 Code
@@ -252,16 +252,38 @@
   value:
+ this.props.results %7C%7C
  %22%22,%0A   
@@ -477,16 +477,171 @@
  %7D%0A  %7D%0A%0A
+  componentDidUpdate(prevProps) %7B%0A    if (this.props.results != prevProps.results) %7B%0A      this.resultsCodeMirror.setValue(this.props.results);%0A    %7D%0A  %7D%0A%0A
   render
@@ -707,16 +707,74 @@
 nt = el%7D
+ className=%7Bthis.props.className%7D style=%7Bthis.props.style%7D
  /%3E%0A    
@@ -1395,96 +1395,8 @@
  );%0A
-    %7D else if (props.pastDelay) %7B%0A      return (%0A        %3Cdiv%3ELoading...%3C/div%3E%0A      );%0A
     
@@ -1516,16 +1516,24 @@
 tsViewer
+%0A       
  CodeMir
@@ -1555,16 +1555,118 @@
 eMirror%7D
+%0A        results=%7Bprops.results%7D%0A        className=%7Bprops.className%7D%0A        style=%7Bprops.style%7D%0A     
  /%3E%0A    

Allow results to be updated as a prop in the results viewer