import Vuex from 'vuex'
import Vue from 'vue'
import ax from './api'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    token: '',
    loggedIn: false,
    username: '',
    error: ''
  },
  mutations: {
    'API_FAIL': function (state, error) {
      state.error = error
    },
    'LOGIN': function (state, creds) {
      state.token = creds.token
      state.loggedIn = true
      state.username = creds.username
    },
    'LOGOUT': function (state) {
      state.token = ''
      state.loggedIn = false
    }
  },
  actions: {
    async getJWTToken (context, credentials) {
      try {
        const response = await ax.post('api-token-auth/', credentials)
        context.commit('LOGIN', {
          token: response.data.token,
          username: credentials.username
        })
      } catch (error) {
        if (error.response) {
          const errorMsg = 'Unable to log in with provided credentials.'
          context.commit('API_FAIL', errorMsg)
          throw errorMsg
        } else {
          const errorMsg = 'Cannot reach server.'
          context.commit('API_FAIL', errorMsg)
          throw errorMsg
        }
      }
    },
    logout (store) {
      store.commit('LOGOUT')
    }
  }
})

export default store