import React from 'react';
import {
    Route,
    Link
} from 'react-router-dom';

import {MdDashboard} from 'react-icons/md';

import Header from './Header';
import Content from './Page/Content';
import Footer from './Footer';

import {withTheme} from '../lib/theme';
import {i18nEvents} from '../lib/i18n';
import {withAuth} from "../feature/Auth";

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

    constructor(props) {
        super(props);

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

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

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

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

        return (
            <React.Fragment>

                <Header
                    moreButtons={(props_item) => (
                        <React.Fragment>
                            {loggedIn ? (
                                <Route path="/:lng" render={(props) => <Link to={'/' + props.match.params.lng + '/dashboard'} className={props_item.className}><MdDashboard color={theme.textColor} size={'1.5em'}/></Link>}/>
                            ) : null}
                        </React.Fragment>
                    )}/>

                <Content loading_lang={this.state.loading_lang}>
                    {routes.map((route, index) => (
                        <Route
                            key={index}
                            path={route.path}
                            exact={route.exact}
                            component={route.component}
                        />
                    ))}
                </Content>

                <Footer/>
            </React.Fragment>
        );
    }
}

export default withTheme(withAuth(FactoryPage));
