import React from 'react'
import App, { Container } from 'next/app'
import classnames from 'classnames'
// import * as Sentry from '@sentry/browser'
import initReactFastclick from 'react-fastclick'
const ThemeContext = React.createContext('theme')

// Sentry.init({
//   dsn: 'https://3dcf09b0b1fa47c68140a350f02a80fe@sentry.io/1729008'
// })
export function ThemeDecorator(Component) {
  return (
   class extends React.Component {
     render() {
     return <ThemeContext.Consumer>
        {(val) => {
            const { en, setLang } = val
            return <Component en={en} setLang={setLang} {...this.props} />
        }}
      </ThemeContext.Consumer>
     }
   }
  
  )
}
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

export { ThemeContext }
// const injectTapEventPlugin = require('react-tap-event-plugin')

if (process.browser) {
  // injectTapEventPlugin()
  initReactFastclick()
}
class MyApp extends App {
  constructor(...props) {
    super(...props)
    this.ctx = {
      en: null,
      setLang: (isEnglish, set = true) => {
        if (this.ctx.en === isEnglish) {
          return
        }
        this.ctx.en = isEnglish
        if (set) {
          window.localStorage.setItem('lan', isEnglish ? 'en' : 'zh')
        }
        this.forceUpdate()
      } 
    }
  }
  // componentDidCatch (error, errorInfo) {
  //   Sentry.withScope(scope => {
  //     Object.keys(errorInfo).forEach(key => {
  //       scope.setExtra(key, errorInfo[key])
  //     })

  //     Sentry.captureException(error)
  //   })

  //   super.componentDidCatch(error, errorInfo)
  // }
  componentDidMount() {
    // window.location.href.
    var lan = getQueryVariable("lang");
    if(lan) {
      window.localStorage.setItem('lan', lan == "en" ? 'en' : 'zh')
      this.ctx.setLang(lan == "en", false)
    } else {
      this.ctx.setLang(window.localStorage.getItem('lan') === 'en', false)
    }
  }
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {}
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

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

    return (
      <React.Fragment>
      <ThemeContext.Provider value={this.ctx}>
        <Container>
          <Component {...pageProps} />
          <div className={classnames({
            en: this.ctx.en,
            zh: this.ctx.en === false
          })} id="modal-anchor"/>
        </Container>
      </ThemeContext.Provider>
      </React.Fragment>
    );
  }
}


export default MyApp
