import React from 'react';
import ReactDOM from 'react-dom';

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
            modified: null,
            rendered: null,
            slug: null,
            source: null,
            title: null,
        };
    }

    componentDidMount() {
        if (!window.location.hash) {
            window.location.hash = "#index";
        }
        const loc = window.location.hash.substring(1);
        fetch(`/p/${loc}`, {headers: {'Accept': 'application/json'}})
            .then(res => res.json())
            .then(
                (res) => {
                    console.log(res);
                    this.setState({
                        loaded: true,
                        modified: res.modified,
                        rendered: res.rendered,
                        slug: res.slug,
                        source: res.source,
                        title: res.title,
                    });
                },
                (error) => {
                    this.setState({
                        page: "failed",
                    });
                }
            );
    }

    render() {
        if (this.state.loaded) {
            return <div dangerouslySetInnerHTML={{__html: this.state.rendered}} />
        } else {
            return <div>Loading...</div>
        }
    }
}

ReactDOM.render(<Page/>, document.getElementById('root'))
