import gql from 'graphql-tag'

import { client } from '@operato/graphql'
import { store } from '@operato/shell'

import { UPDATE_PERMISSION } from '../actions/permissions'

const INITIAL_STATE = {
  boardPermissions: ['Viewer', 'Modeller']
}

;(async () => {
  var response = await client.query({
    query: gql`
      {
        boardPermissions
      }
    `
  })

  if (response.data.boardPermissions) {
    store.dispatch({
      type: UPDATE_PERMISSION,
      state: { boardPermissions: response.data.boardPermissions }
    })
  }
})()

const permissions = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case UPDATE_PERMISSION:
      return {
        ...INITIAL_STATE,
        ...action.state
      }
    default:
      return state
  }
}

export default permissions
