import React from 'react';
import {withNamespaces} from 'react-i18next';
import {Redirect} from 'react-router-dom';

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

import ArticleDetailBaseEdit from './ArticleDetailBaseEdit';
import {withPusher} from "../../component/Pusher/Pusher";
import {storeArticle} from "./Stores/Article";
import {cancelPromise} from "../../component/cancelPromise";

const styling = theme => ({
    wrapper: {
        overflow: 'hidden'
    },
});

class ArticleCreate extends React.Component {
    state = {
        saving: false,
        newArticle: false,
    };


    pushNewArticle = (name, tag) => {
        const {createArticle, cancelPromise} = this.props;

        this.setState({saving: 'progress'});
        cancelPromise(createArticle(this.props.section, name, tag))
            .then((data) => {
                if(data.error) {
                    this.setState({saving: 'error'});
                    return;
                }

                this.setState({
                    saving: 'success',
                    newArticle: data.success
                });

                setTimeout(() => {
                    this.setState({
                        newArticle: false
                    });
                }, 0);

                setTimeout(() => {
                    this.setState({saving: false});
                }, 4000);
            })
            .catch((err) => {
                if(err && !err.cancelled) {
                    this.setState({saving: 'error'});
                }
            });
    };

    render() {
        const {
            section
        } = this.props;

        return (
            <React.Fragment>
                {
                    (
                        this.state.newArticle
                    ) ? <Redirect to={'/' + i18n.languages[0] + '/content/' + this.props.section + '/' + this.state.newArticle}/>
                        : null
                }
                <ArticleDetailBaseEdit pushBaseData={this.pushNewArticle}
                                       articleInfo={{section: section}}
                                       open={true}
                                       saving={this.state.saving}
                                       create={true}
                />
            </React.Fragment>
        )
    };
}

export default withNamespaces('page--content-article')(withPusher(cancelPromise(storeArticle(withTheme(injectSheet(styling)(ArticleCreate))))));