import React, { Component } from "react";
import { Editor } from 'react-draft-wysiwyg';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import '../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import * as actions from './actions.js';

class Blog extends Component {
    constructor( props ) {
        super( props );
        this.state = {
            editorState: EditorState.createEmpty(),
        };
    }

    componentDidMount( event ) {
        this.getBlogEntries();
    }

    componentDidUpdate(prevProps, prevState) {
        if ( prevState.currentEntry !== this.state.currentEntry ) {
            console.log(this.state.currentEntry);
            const blocksFromHtml = htmlToDraft(this.state.currentEntry.data.content);
            const { contentBlocks, entityMap } = blocksFromHtml;
            const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
            const editorState = EditorState.createWithContent(contentState);
            this.setState({
                editorState: editorState,
            });
        };
    }

    getBlogEntries( queueDisplayElement ) {
        const entriesPromise = actions.entriesPromise();
        actions.setSpinerVisible( true );

        entriesPromise.then(entriesResponse => {
            const oEntries = JSON.parse( entriesResponse );
            const aEntriesSorted = actions.sortObjectIds( oEntries );
            let sidebarButtonItems = [];

            sidebarButtonItems = aEntriesSorted.map(entryId => {
                function callDisplayEntry () { // Calls the display function and binds this
                    const that = this;
                    actions.displayEntry( entryId, that );
                }
                return (
                    <button
                        key={ 'sidebarbuttonitem'+entryId }
                        className={ 'list-group-item list-group-item-action ' }
                        id={ "sidebarButton_" + entryId }
                        type='button'
                        onClick={ callDisplayEntry.bind( this ) }>
                        
                        { oEntries[ entryId ].title }
                    </button>
                );
            });

            this.setState({
                ...this.state,
                oEntries: oEntries,
                sidebarButtonItems: sidebarButtonItems,
                queueDisplay: queueDisplayElement || '',
            });
            actions.setSpinerVisible( false );
        });
    }

    onEditorStateChange = (editorState) => {
        console.log("Entry typed text: ", draftToHtml(convertToRaw(editorState.getCurrentContent())));
        this.setState({
            editorState,
        });
    }

    saveJson = (modifiedData, needReload, queueDisplayItem) => {
        const saveJsonPromise = actions.postJsonPromise( modifiedData, 'blog' );

        saveJsonPromise.then( () => {
            if ( needReload !== undefined && needReload !== null ) {
                window.location.reload();
            } else {
                actions.setSpinerVisible( false );
                this.setSideBarItems( queueDisplayItem !== undefined ? queueDisplayItem : '' );
            }
        } );
    }

    render() {
        const { editorState } = this.state;
        return (
            <div className="row">
                {/* THE SIDEBAR */}
                <div className="col-md-3 bookSearch">
                    <div>
                        <button
                            onClick={ this.createNewEntry }
                            type="button"
                            className={"btn btn-info"}
                        >Agregar nueva entrada de blog</button>
                    </div>
                    <div>
                        <input
                            type="search"
                            name="entryListFilter"
                            id="entryListFilter"
                            onKeyUp={() => {actions.filterBySearch("entryListFilter", "list-group", "button" )}}
                            placeholder="Ingresa el nombre de la entrada"
                        />
                    </div>
                    <div className="bookList" id="bookList">
                        <div className="list-group" id="list-group">
                            {this.state.sidebarButtonItems}
                        </div>
                    </div>
                </div>
                <div id="main-form">
                    <div className="col-md-9">
                        <Editor
                            editorState={editorState}
                            toolbarClassName="toolbarClassName"
                            wrapperClassName="wrapperClassName"
                            editorClassName="editorClassName"
                            onEditorStateChange={this.onEditorStateChange}
                        />
                    </div>
                </div>
            </div>
        );
    }
}

export default Blog;