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 apiGroup from './ApiGroup';

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);
        apiGroup.offList('group-list');
    }

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

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

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

            if('object' === typeof this.state.data) {
                this.state.data.forEach((group) => {
                    content.push({
                        path: match.url + '/' + group.id,
                        lbl: {txt: group.name},
                    })
                });
            }

            return content;
        };

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

        return (
            <React.Fragment>
                {
                    true === this.state.loaded ?
                        <Sidebar top={SideBarTop}
                                 center={(props => <Nav path='/shop/objects' 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--shop')(withTheme(injectSheet(theming)(SectionList)));