import React from 'react';

import {ApiRequest, GET} from '../../lib/ApiRequest';
import {withTheme} 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";

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

class SectionList extends React.Component {

    state = initialState;

    componentWillUnmount() {
        this.setState(initialState);
    }

    componentDidMount() {
        this.setState({loaded: 'progress'});

        (new ApiRequest('api', GET, 'content/section'))
            .debug(true)
            .exec()
            .then((res) => {
                if(res && res.data) {
                    this.setState({
                        data: res.data,
                        loaded: true
                    });
                } else {
                    this.setState({
                        loaded: 'error'
                    });
                }
            })
            .catch(() => {
                this.setState({
                    loaded: 'error'
                });
            });
    }

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

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

            for(let sid in this.state.data) {
                if(this.state.data.hasOwnProperty(sid)) {
                    content.push({
                        path: match.url + '/' + sid,
                        lbl: {txt: sid},
                    })
                }
            }

            return content;
        };

        return (
            <React.Fragment>
                {
                    true === this.state.loaded ?
                        <Sidebar
                            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 withTheme(SectionList);