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

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

import Loading from "../../component/LoadingSmall";
import Nav from "../../component/Nav/Nav";
import Sidebar from "../../layout/ControlPanel/Sidebar";
import StyleGrid from "../../lib/StyleGrid";
import {storeSection} from "./Stores/Section";
import {withBackend} from "../../feature/BackendConnect";

const theming = (theme) => ({
    sidebarTop: {
        margin: 'auto ' + theme.gutter.base + 'px',
        [StyleGrid.smUp]: {
            margin: '0 0 ' + theme.gutter.base * 2 + 'px 0',
        }
    }
});

class SectionList extends React.Component {

    componentDidMount() {
        const {loadSectionList} = this.props;
        loadSectionList();
    }

    componentDidUpdate(prevProps) {
        if(prevProps.hook_active !== this.props.hook_active) {
            const {loadSectionList, history} = this.props;
            loadSectionList(true);
            history.push('/' + i18n.languages[0] + '/content');
        }
    }

    render() {
        const {
            t, classes,
            sections, loadingSections
        } = this.props;

        const navContent = (match) => {
            let content = [];

            sections.forEach((section) => {
                content.push({
                    path: match.url + '/' + section.id,
                    lbl: {txt: section.name},
                })
            });

            return content;
        };

        const SideBarTop = p => (<p className={classes.sidebarTop}>{t('sidebar.section-list')}</p>);

        return (
            <React.Fragment>
                {
                    <Sidebar top={SideBarTop}
                             center={(props => (
                                 'progress' === loadingSections || 'error' === loadingSections ?
                                     <Loading
                                         center={true}
                                         errorWarning={'error' === loadingSections}
                                     /> :
                                     true === loadingSections ? <Nav path='/content' content={navContent}/> : null
                             ))}
                    />
                }

                {this.props.routes ? this.props.routes.map((route, i) => (
                    route.sidebar ?
                        <RouteCascaded key={i} {...route} component={route.sidebar}/> :
                        null
                )) : null}
            </React.Fragment>
        )
    };
}

export default withNamespaces('page--content-article')(withBackend(withRouter(storeSection(withTheme(injectSheet(theming)(SectionList))))));