import React from 'react';
import './app.less';

import { router } from './router';
import { getLang } from '../common/locales';

import DemoNav from './components/DemoNav.jsx';
import DemoSection from './components/DemoSection.jsx';

class App extends React.Component {
  constructor(props) {
    super(props);
    const currentRoute = this.getCurrentRoute();
    this.state = {
      currentRoute: currentRoute,
    };
  }

  componentDidMount() {
    window.addEventListener('hashchange', this.hashchange);
  }

  componentWillUnmount() {
    window.removeEventListener('hashchange', this.hashchange);
  }

  hashchange = () => {
    const currentRoute = this.getCurrentRoute();
    this.setState({ currentRoute });
  };

  getCurrentRoute = () => {
    const locationHash = window.location.hash;
    const currentRoute = router.routes.find((item) => item.hash === locationHash);
    if (currentRoute) return currentRoute;
    const currentLang = getLang();
    const homeRoute = router.routes.find((item) => item.name === currentLang);
    return homeRoute || {};
  };

  render() {
    const { currentRoute } = this.state;
    const Comp = currentRoute.component || null;
    return (
      <div>
        <DemoNav currentRoute={currentRoute} />
        <DemoSection>{Comp && <Comp />}</DemoSection>
      </div>
    );
  }
}

export default App;
