import React from 'react';
import App, { Container } from 'next/app';
import { MuiThemeProvider } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import JssProvider from 'react-jss/lib/JssProvider';
import getPageContext from '../src/getPageContext';

import Router from 'next/router'
import getConfig from 'next/config'
import Head from 'next/head'

import { initGA, logPageView } from '../utils/analytics'


const { publicRuntimeConfig } = getConfig()
class MyApp extends App {
  constructor(props) {
    super(props);
    this.pageContext = getPageContext();
  }

  pageContext = null;

  static async getInitialProps({ Component, ctx }) {
    let err = false;
    const res = await fetch(publicRuntimeConfig.wordpressUrl.menu)
    const menu = await res.json()


    if (menu.data && menu.data.status != 200)
      err = true;

    let pageProps = {}

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx)
    }

    return { pageProps: { ...pageProps }, menu, err }
  }

  componentDidMount() {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles && jssStyles.parentNode) {
      jssStyles.parentNode.removeChild(jssStyles);
    }
    if (process.env.DEV !== 1) {
      initGA()
      logPageView()
      Router.router.events.on('routeChangeComplete', logPageView)
    }
  }

  componentWillUnmount() {
    if (process.env.DEV !== 1) {
      Router.router.events.off('routeChangeComplete', logPageView);
    }
  }

  render() {
    const { Component, pageProps, menu } = this.props;

    return (
      <Container>
        <Head>
          <title>e-declic</title>
        </Head>
        {/* Wrap every page in Jss and Theme providers */}
        <JssProvider
          registry={this.pageContext.sheetsRegistry}
          generateClassName={this.pageContext.generateClassName}
        >
          {/* MuiThemeProvider makes the theme available down the React
              tree thanks to React context. */}
          <MuiThemeProvider
            theme={this.pageContext.theme}
            sheetsManager={this.pageContext.sheetsManager}
          >
            {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
            <CssBaseline />
            {/* Pass pageContext to the _document though the renderPage enhancer
                to render collected styles on server side.
                messagingSingleton={messagingSingleton} */}
            <Component pageContext={this.pageContext} menu={menu}  {...pageProps} />
          </MuiThemeProvider>
        </JssProvider>
        <noscript>This is a modern pwa site. You must allow javascript !</noscript>
      </Container>
    );
  }
}

export default MyApp;
