import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloLink } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { onError } from 'apollo-link-error'

import { navigate, store } from '../store'
import { authError } from './actions-auth'
import ThingsSnackbar from '../../components/things-snackbar'

const GRAPHQL_URI = '/graphql'
const defaultOptions = {
  watchQuery: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'ignore'
  },
  query: {
    fetchPolicy: 'no-cache',
    errorPolicy: 'all'
  }
}

const cache = new InMemoryCache()

const client = new ApolloClient({
  defaultOptions,
  cache,
  link: ApolloLink.from([
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors)
        graphQLErrors.map(({ message, locations, path }) => {
          console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
          ThingsSnackbar.toast(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
        })

      if (networkError) {
        switch (networkError.statusCode) {
          case 401:
            if (location.pathname !== '/signup') {
              store.dispatch(authError(networkError))
              store.dispatch(navigate('/signin'))
            }
            break
          default:
          // console.log(`[Network error]: networkError`)
        }
      }
    }),
    new HttpLink({
      uri: GRAPHQL_URI
    })
  ])
})

export default client
