import { v4 as uuid } from 'uuid'
import { SubscriptionClient } from 'subscriptions-transport-ws'
import ApolloClient from 'apollo-client'
import VueApollo from 'vue-apollo'
import { defaultDataIdFromObject, InMemoryCache } from 'apollo-cache-inmemory'
import * as Cookie from 'js-cookie'
import { ref } from 'vue'

export const clientId = uuid()

const server = process.env.NODE_ENV === 'production' ? 'wss://turnenaufzeit.de/gql' : 'ws://localhost:3000/graphql'

const client = new SubscriptionClient(server, {
  reconnect: true,
  connectionParams: () => {
    return {
    clientId,
    token: Cookie.get('token'),
  }}
})

const graphQL = new ApolloClient({
  link: client,
  cache: new InMemoryCache({
    dataIdFromObject: object => {
      switch (object.__typename) {
        default: return defaultDataIdFromObject(object)
      }
    }
  }),
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
    },
    query: {
      fetchPolicy: 'no-cache',
    },
  },
})

export default new VueApollo({
  defaultClient: graphQL,
})

export const useGraphQL = () => {
  const connected = ref(graphQL.link?.client?.readyState === 1)

  graphQL.link.on('connecting', () => { connected.value = false })
  //graphQL.link.on('connected', () => { connected.value = true })
  graphQL.link.on('reconnecting', () => { connected.value = false })
  graphQL.link.on('reconnected', () => { connected.value = true })
  graphQL.link.on('disconnected', () => { connected.value = false })
  graphQL.link.on('error', () => { connected.value = false })

  return { connected }
}