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

import {withTheme, injectSheet} from '../../lib/theme';
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 {storeGroup} from "./Stores/Group";
import {withBackend} from "../../feature/BackendConnect";
import {i18n} from "../../lib/i18n";

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 {loadGroupList} = this.props;
        loadGroupList();
    }

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

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

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

            groups.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>
                {
                    <Sidebar top={SideBarTop}
                             center={(props => (
                                 'progress' === loadingGroups || 'error' === loadingGroups ?
                                     <Loading
                                         center={true}
                                         errorWarning={'error' === loadingGroups}
                                     /> :
                                     true === loadingGroups ? <Nav path='/shop/products' 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--shop')(withBackend(withTheme(storeGroup(injectSheet(theming)(SectionList)))));