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 Editor from '../../component/EditorLoader';
import {withTheme, injectSheet} from '../../lib/theme';
import StyleGrid from "../../lib/StyleGrid";

const styling = theme => ({
    wrapper: {
        width: '100%',
        margin: '30px 0'
        //height: '100%'
    },
    title: {
        marginBottom: '3px'
        //height: '100%'
    },
    textArea: {
        flexGrow: 5,
        display: 'block',
        width: '100%',
        minHeight: '150px',
        //height: '20%',
        border: '1px solid transparent',
        background: 'transparent',
        padding: '12px',
        fontSize: '1rem',
        letterSpacing: '0.25px',
        lineHeight: '1.3rem',
        fontFamily: 'Inconsolata, monospace',
        [StyleGrid.smUp]: {
            minHeight: '250px',
        }
    },
    controls: {
        flexGrow: 0,
        marginTop: '-6px',
        paddingLeft: '1px',
        display: 'flex',
    },
    edited: {
        display: 'flex',
        paddingLeft: '6px'
    },
});

const btnstyle = {
    marginLeft: '-1px'
};

const initialState = {
    data: {},
    content: false,
    render: true,
    loadedEditor: false
};

class ArticleDetailMainText extends React.Component {

    state = initialState;

    constructor(props) {
        super(props);

        this.evt = {
            generic: {},
            html: {},
            md: {},
        };
    }

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

    componentDidUpdate(prevProps) {
    }

    /**
     * A fn prop that is called when the editor has been mounted - then buttons are displayed
     * But buttons get not deleted
     */
    setLoadedEditor = () => {
        this.setState({
            loadedEditor: true
        })
    };

    /**
     * Serve the content as file download in Markdown or HTML
     * @param {String} content
     * @param {Boolean} asMd true saves MarkDown and false HTML
     *
     * @todo does not work in PWA Mode/as installed homepage on smartphones, the blob is opened in a new tab but saving is not triggered
     */
    _downloadTxtFile = (content, asMd = true) => {
        const {section, article} = this.props;

        let element = document.createElement("a");
        let file = new Blob([content], {type: (asMd ? 'text/markdown; charset=UTF-8' : 'text/html')});
        element.href = URL.createObjectURL(file);
        element.download = section + '-' + article + '-MainText.' + (asMd ? 'txt' : 'html');
        document.body.appendChild(element);
        element.click();
        element.remove();
    };

    exportHtml = (evt = false) => {
        if(evt) {
            this.evt.html = evt;
            return;
        }

        return this.evt.html();
    };

    exportMd = (evt = false) => {
        if(evt) {
            this.evt.md = evt;
            return;
        }

        return this.evt.md();
    };

    save = (evt = false) => {
        if(evt) {
            this.evt.generic = evt;
            return;
        }

        return this.evt.generic();
    };

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

        this.props.saveFn(this.save());
    };

    triggerHtml = () => {
        this._downloadTxtFile(this.exportHtml(), false);
    };

    triggerMd = () => {
        this._downloadTxtFile(this.exportMd());
    };

    reset = () => {
        if(this.props.content) {
            this.setState({
                render: false
            });

            setTimeout(() => {
                this.setState({
                    render: true
                });
            }, 1);
        }
    };

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

        return (
            <React.Fragment>
                {
                    (this.props.content ? (
                        <div className={classes.wrapper}>
                            <h3 className={classes.title}>{t('maintxt.title')}</h3>

                            {this.state.render ?
                                // only when true, enables to rerender to reset
                                <Editor
                                    markdown={this.props.content}
                                    afterInit={this.setLoadedEditor}
                                    save={this.save}
                                    saveHtml={this.exportHtml}
                                    saveMd={this.exportMd}
                                /> : null}

                            {this.state.loadedEditor ?
                                <div className={classes.controls}>
                                    <Button onClick={this.trigger} style={btnstyle}>{t('maintxt.save')}</Button>
                                    {/* exporter does not work with current JS in PWA mode/as installed homepage */
                                        (window.matchMedia('(display-mode: standalone)').matches) ? null :
                                            <React.Fragment>
                                                <Button onClick={this.triggerHtml} style={btnstyle}>{t('maintxt.exportHtml')}</Button>
                                                <Button onClick={this.triggerMd} style={btnstyle}>{t('maintxt.exportMd')} </Button>
                                            </React.Fragment>}
                                    <Button onClick={this.reset} style={btnstyle}>{t('maintxt.reset')} </Button>
                                    {saving ?
                                        ('progress' === saving || 'error' === saving ?
                                            <React.Fragment>
                                                <Loading style={{
                                                    wrapper: {margin: 0},
                                                    item: ('error' === saving ? {borderColor: theme.errorColor} : {}),
                                                }}/>

                                            </React.Fragment> :
                                            ('success' === saving ?
                                                <MdDone/> : null))
                                        : null}
                                </div>
                                : null}
                        </div>
                    ) : null)
                }
            </React.Fragment>
        )
    };
}

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