import React from 'react'
import { Provider } from 'mobx-react'

import initRootStore from '../stores/init'
import { GAWraper } from '../components'

import {
  makeGQClient,
  queryStringToJSON,
  getSubPath,
  ROUTE,
  THREAD,
  BStore,
} from '../utils'

import {
  ThemeWrapper,
  MultiLanguage,
  Sidebar,
  Preview,
  Doraemon,
  Route,
  BodyLayout,
  Header,
  Banner,
  Content,
  Footer,
} from '../containers'

import { P } from '../containers/schemas'

// try to fix safari bug
// see https://github.com/yahoo/react-intl/issues/422
global.Intl = require('intl')

async function fetchData(props) {
  const token = BStore.cookie.from_req(props.req, 'jwtToken')
  const gqClient = makeGQClient(token)

  const videoId = getSubPath(props)

  // query data
  const sessionState = gqClient.request(P.sessionState)
  const video = gqClient.request(P.video, { id: videoId })
  const subscribedCommunities = gqClient.request(P.subscribedCommunities, {
    filter: {
      page: 1,
      size: 30,
    },
  })

  return {
    ...(await sessionState),
    ...(await video),
    ...(await subscribedCommunities),
  }
}

export default class Index extends React.Component {
  static async getInitialProps(props) {
    const { req, asPath } = props
    const isServer = !!req
    if (!isServer) return {}

    console.log('SSR (video--) queryStringToJSON: ', queryStringToJSON(asPath))
    /* console.log('SSR extractThreadFromPath -> ', extractThreadFromPath(props)) */
    const { sessionState, video, subscribedCommunities } = await fetchData(
      props
    )
    /* const videoId = getSubPath(props) */
    /* console.log('getSubPath --> thread: ', thread) */

    return {
      langSetup: {},
      account: {
        user: sessionState.user || {},
        isValidSession: sessionState.isValid,
        userSubscribedCommunities: subscribedCommunities,
      },
      route: { mainPath: ROUTE.VIDEO, subPath: video.id },
      viewing: {
        video,
        activeThread: THREAD.VIDEO,
        community: video.communities[0],
      },
    }
  }

  constructor(props) {
    super(props)
    this.store = initRootStore({ ...props })
  }

  render() {
    return (
      <Provider store={this.store}>
        <GAWraper>
          <ThemeWrapper>
            <Route />
            <MultiLanguage>
              <Sidebar />
              <Preview />
              <Doraemon />
              <BodyLayout>
                <Header />
                <Banner />
                <Content />
                <Footer />
              </BodyLayout>
            </MultiLanguage>
          </ThemeWrapper>
        </GAWraper>
      </Provider>
    )
  }
}

@@ -118,16 +118,27 @@
 GAWraper
+, ErrorPage
  %7D from 
@@ -183,29 +183,8 @@
 nt,%0A
-  queryStringToJSON,%0A
   ge
@@ -222,16 +222,32 @@
 BStore,%0A
+  ssrAmbulance,%0A
 %7D from '
@@ -1220,244 +1220,274 @@
     
-const %7B req, asPath %7D = 
+let resp%0A    try %7B%0A      resp = await fetchData(
 props
+)
 %0A    
-const isServer = !!req%0A    if (!isServer) return %7B%7D%0A%0A    console.log('SSR (video--) queryStringToJSON: ', queryStringToJSON(asPath))%0A    /* console.log('SSR extractThreadFromPath -%3E ', extractThreadFrom
+%7D catch (%7B response: %7B errors %7D %7D) %7B%0A      if (ssrAmbulance.hasLoginError(errors)) %7B%0A        resp = await fetchData(props, %7B realname: false %7D)%0A      %7D else %7B%0A        return %7B statusCode: 404, target: getSub
 Path
@@ -1493,20 +1493,33 @@
 h(props)
-) */
+ %7D%0A      %7D%0A    %7D%0A
 %0A    con
@@ -1574,143 +1574,12 @@
 %7D = 
-await fetchData(%0A      props%0A    )%0A    /* const videoId = getSubPath(props) */%0A    /* console.log('getSubPath --%3E thread: ', thread) */
+resp
 %0A%0A  
@@ -2015,160 +2015,458 @@
     
-this.store = initRootStore(%7B ...props %7D)%0A  %7D%0A%0A  render() %7B%0A    return (%0A      %3CProvider store=%7Bthis.store%7D%3E%0A        %3CGAWraper%3E%0A          %3CThemeWrapper%3E%0A
+const store = props.statusCode%0A      ? initRootStore(%7B langSetup: %7B%7D %7D)%0A      : initRootStore(%7B ...props %7D)%0A%0A    this.store = store%0A  %7D%0A%0A  render() %7B%0A    const %7B statusCode, target %7D = this.props%0A%0A    return (%0A      %3CProvider store=%7Bthis.store%7D%3E%0A        %3CGAWraper%3E%0A          %3CThemeWrapper%3E%0A            %7BstatusCode ? (%0A              %3CErrorPage errorCode=%7BstatusCode%7D page=%22post%22 target=%7Btarget%7D /%3E%0A            ) : (%0A              %3CReact.Fragment%3E%0A    
     
@@ -2479,24 +2479,28 @@
   %3CRoute /%3E%0A
+    
             
@@ -2529,16 +2529,20 @@
         
+    
 %3CSidebar
@@ -2559,16 +2559,20 @@
         
+    
 %3CPreview
@@ -2571,24 +2571,28 @@
 %3CPreview /%3E%0A
+    
             
@@ -2620,16 +2620,20 @@
         
+    
 %3CBodyLay
@@ -2629,32 +2629,36 @@
    %3CBodyLayout%3E%0A
+    
                 
@@ -2684,16 +2684,20 @@
         
+    
 %3CBanner 
@@ -2695,24 +2695,28 @@
  %3CBanner /%3E%0A
+    
             
@@ -2747,16 +2747,20 @@
         
+    
 %3CFooter 
@@ -2776,16 +2776,20 @@
         
+    
 %3C/BodyLa
@@ -2786,32 +2786,36 @@
   %3C/BodyLayout%3E%0A
+    
             %3C/Mu
@@ -2819,32 +2819,79 @@
 /MultiLanguage%3E%0A
+              %3C/React.Fragment%3E%0A            )%7D%0A
           %3C/Them

support error handling