import React from 'react';
import {withNamespaces} from 'react-i18next';
import {MdDone} from 'react-icons/md';

import Loading from "../../component/Loading";

import {ButtonSmall as Button} from '../../component/Form';
import DocTreeEditor from "../../component/DocTree/EditorLoader";

import {withTheme, injectSheet} from '../../lib/theme';
import {ApiRequest, GET} from "../../lib/ApiRequest";

import {SaveSingle} from '../../component/ContentStore';

const styling = theme => ({
    wrapper: {
        margin: '30px 0'
    },
    groups: {}
});

const initialState = {
    pageType: {},
    blockSelection: {},
    loaded: false
};

class ArticleDetailDocTree extends React.Component {

    state = initialState;

    constructor(props) {
        super(props);

        this.saveEvt = new SaveSingle();
    }

    componentWillUnmount() {
        this.setState(initialState);
    }

    //
    // Api Fetch and Push

    fetch(pagetype) {
        this.setState({loaded: 'progress'});

        const fetchPageType = new Promise(((resolve, reject) => {
            (new ApiRequest('api', GET, 'content/page-type/' + pagetype))
                .debug(true)
                .header({})
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        resolve(res.data);
                    } else {
                        reject();
                    }
                })
                .catch(() => {
                    reject();
                });
        }));

        const fetchBlockSelection = new Promise(((resolve, reject) => {
            (new ApiRequest('api', GET, 'content/blocks'))
                .debug(true)
                .header({})
                .exec()
                .then((res) => {
                    if(res && res.data) {
                        resolve(res.data);
                    } else {
                        reject();
                    }
                })
                .catch(() => {
                    reject();
                });
        }));

        fetchPageType.then((page_type) => {
            fetchBlockSelection.then((block_selection) => {
                this.setState({
                    pageType: page_type,
                    blockSelection: block_selection,
                    loaded: true
                });
            }).catch(() => {
                this.setState({
                    loaded: 'error'
                });
            });
        }).catch(() => {
            this.setState({
                loaded: 'error'
            });
        });
    }

    trigger = () => {
        if(!this.props.saveFn) {
            console.error('ArticleDocTree: can not save, no prop `saveFn` binding exits.');
            return;
        }

        this.props.saveFn(this.saveEvt.trigger());
    };

    componentDidUpdate(prevProps) {
        if(
            prevProps.pageType !== this.props.pageType ||
            prevProps.docTree !== this.props.docTree
        ) {
            this.fetch(this.props.pageType);
        }
    }

    componentDidMount() {
        if(this.props.pageType) {
            this.fetch(this.props.pageType);
        }
    }

    render() {
        const {t, classes, saving, theme} = this.props;
        const {addSave, rmSave} = this.saveEvt;

        return (
            <div className={classes.wrapper}>

                <h3 style={{width: '100%'}}>{t('doctree.title')}</h3>

                {('progress' === this.state.loaded || 'error' === this.state.loaded ?
                    <Loading
                        style={{
                            wrapper: {margin: 0},
                        }}
                        errorWarning={'error' === this.state.loaded}
                    /> :
                    null)}

                {true === this.state.loaded ?
                    <DocTreeEditor data={this.props.docTree}
                                   blockroot={this.state.pageType.block_root}
                                   blockSelection={this.state.blockSelection}
                                   addSave={addSave}
                                   rmSave={rmSave}
                    /> :
                    null}

                <Button onClick={this.trigger}>{t('doctree.save')} {('success' === saving ?
                    <MdDone/> : null)}</Button>

                {saving ?
                    ('progress' === saving || 'error' === saving ?
                        <React.Fragment>
                            <Loading style={{
                                wrapper: {margin: 0},
                                item: ('error' === saving ? {borderColor: theme.errorColor} : {}),
                            }}/>

                        </React.Fragment> : null)
                    : null}
            </div>
        )
    };
}

export default withNamespaces('page--content-article')(withTheme(injectSheet(styling)(ArticleDetailDocTree)));