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

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

import Loading from "../../component/Loading";
import Nav from "../../component/Nav/Nav";
import Sidebar from "../../layout/ControlPanel/Sidebar";
import StyleGrid from "../../lib/StyleGrid";
import apiSection from './ApiSection';

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

const initialState = {
    data: [],
    loaded: false
};

class SectionList extends React.Component {

    state = initialState;

    componentWillUnmount() {
        this.setState(initialState);
        apiSection.offList('section-list');
    }

    componentDidMount() {
        apiSection.onList(
            (state) => {
                this.setState({loaded: state});
            },
            (data) => {
                this.setState({data});
            },
            'section-list'
        )
    }

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

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

            this.state.data.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>
                {
                    true === this.state.loaded ?
                        <Sidebar top={SideBarTop}
                                 center={(props => <Nav path='/content' content={navContent}/>)}
                        /> :
                        ('progress' === this.state.loaded || 'error' === this.state.loaded ?
                            <Loading style={{
                                wrapper: {margin: 0},
                                item: ('error' === this.state.loaded ? {borderColor: theme.errorColor} : {}),
                            }}/> :
                            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')(withTheme(injectSheet(theming)(SectionList)));