/* App starts here */
import React from "react";
import ReactMarkdown from "react-markdown/with-html";
import CodeBlock from "./CodeBlock";

class MarkdownLoader extends React.Component {
  constructor(props) {
    super(props);
    this.state= {
      src: props.src,
      loaded: "",
      loading: "",
      markdown: props.markdown ? props.markdown : "Loading..."
    };
    this.loadContent = this.loadContent.bind(this);
  }

  componentDidMount() {
    this.loadContent();
  }

  componentDidUpdate(previous) {
    if (this.props.src != previous.src) {
      this.state.src = this.props.src;
      this.loadContent();
    }
  }

  loadContent() {
    if (!this.state.src) {
      return;
    }
    
    console.log("Loading " + this.state.src, this.props.src);

    this.state.loading = this.state.src;
    fetch(this.state.src.match(/^https?:\/\//) ? this.state.src : "./docs/" + this.state.src)
      .then((response) => {
      if (response.ok) {
        return response.text();
      } else {
        throw Error(response.statusText)
      }
    }).then((result) => {
      /* If 'result' doesn't already contain a link to the GitLab page, add it
       * to the end of the content. */
      this.setState({
        loading: null,
        loaded: this.state.loading,
        markdown: result
      });
    }, (error) => {
      this.setState({
        markdown: this.props.fallback ? this.props.fallback : [
          "# Error loading " + this.state.src,
          "",
          error.message
        ].join("\n")
      });
    });
  }

  render() {
    const isDebug = window.location.search.match(/debug(=(y|t|1).*)?/);
    return (
      <div className="MarkdownLoader">
        <ReactMarkdown
          className="Markdown"
          escapeHtml={false}
          source={ this.state.markdown }
          renderers={{ code: CodeBlock }} 
        />
        { (isDebug) &&
          <div className='gitlab-banner'>
            <a target="_new" href={"https://gitlab.devtools.intel.com/vtt/sws/osgc/agama-website/edit/master/docs/" + this.state.src }>edit on gitlab</a>
          </div>
        }
      </div>
    )
  }
}

export default MarkdownLoader;