import React from 'react';

import Nav from '../component/Nav/Nav';

import Header from './Header';
import Sidebar from './ControlPanel/Sidebar';
import Content from './ControlPanel/Content';

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

const styling = theme => ({
    center: {
        display: 'flex',
        height: '100%',
        width: '100%',
        flexGrow: 2,
        flexDirection: 'column',
        [StyleGrid.smUp]: {
            marginTop: 0,
            flexDirection: 'row',
            overflow: 'auto',
        },
    }
});

class FactoryPage extends React.Component {
    state = {
        loading_lang: false
    };

    constructor(props) {
        super(props);

        this.evt_id = {
            languageChanging: null,
            languageChanged: null
        };
    }

    componentWillUnmount() {
        i18nProvider.off('languageChanging', this.evt_id.languageChanging);
        i18nProvider.off('languageChanged', this.evt_id.languageChanged);
    }

    componentDidMount() {
        this.evt_id.languageChanging = i18nProvider.on('languageChanging', (() => {
            this.setState({loading_lang: true});
        }));
        this.evt_id.languageChanged = i18nProvider.on('languageChanged', (() => {
            this.setState({loading_lang: false});
        }));
    }

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

        return (
            <React.Fragment>
                <Header style={{background: 'rgba(50, 50, 50, 0.3)'}}/>

                <div className={classes.center}>
                    <Sidebar center={(props) => <Nav content={this.props.nav} {...props} notxt={props.notxt}/>} textToggle={true}/>

                    {/* routing for one level of sidebar */}
                    {routes.map((route, i) => (
                        route.sidebar ?
                            <RouteCascaded key={i} {...route} component={route.sidebar}/> :
                            null
                    ))}

                    {/* routing for all levels of content */}
                    <Content loading_lang={this.state.loading_lang}>
                        {routes.map((route, i) => (
                            route.content ?
                                <RouteCascaded key={i} {...route} exact={true} component={route.content} childComponent='content'/> :
                                null
                        ))}
                    </Content>
                </div>
            </React.Fragment>
        );
    }
}

export default withTheme(injectSheet(styling)(FactoryPage));
