import Vue from 'vue';
import Vuex from 'vuex';

import router from './route';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: 'Kittisak Maneewong',
    jwt: localStorage.getItem('access_token') || null,
    jwt_employer: localStorage.getItem('access_token_employer') || null,
    dialog: false,
    snackbar: {
      show: false,
      color: null,
      text: null
    }
  },
  mutations: {
    setJwt (state, payload) {
      state.jwt = payload
    },
    setJwtEmployer (state, payload) {
      state.jwt_employer = payload
    },
    setDialog (state, payload) {
      state.dialog = payload
    },
    setSnackbar (state, payload) {
      state.snackbar = payload
    }
  },
  actions: {
    login ({commit}, payload) {
      return new Promise((resolve, reject) => {
        axios.post('api/auth/login', payload)
        .then(res => {
          if (payload.role == 1) {
            localStorage.setItem('access_token', res.data.token)
            commit('setJwt', res.data.token)
          } else {
            localStorage.setItem('access_token_employer', res.data.token)
            commit('setJwtEmployer', res.data.token)
          }
          commit('setSnackbar', {
            show: true,
            color: 'success',
            text: 'เข้าสู่ระบบสำเร็จ!'
          })
          commit('setDialog', false)
          console.log(res)
          resolve(res)
        })
        .catch(err => {
          console.log(err.response)
          reject(err.response)
        })
      })
    },
    register ({commit}, payload) {
      commit('setLoading2', true)
      return new Promise((resolve, rejeect) => {
        axios.post('api/auth/register', payload)
          .then(res => {
            console.log(res)
            commit('setError', null)
            resolve(res)
          })
          .catch(err => {
            console.log(err.response)
            if (err.response.data == '{"email":["The email has already been taken."]}') {
              this.$store.commit('setError', 'error')
            }
            rejeect(err.response)
          })
        commit('setLoading2', false)
      })
    }
  },
  getters: {
    welcome (state) {
      return state.message
    },
    getJwt (state) {
      return state.jwt
    },
    getJwtEmployer (state) {
      return state.jwt_employer;
    },
    getDialog (state) {
      return state.dialog
    },
    getSnackbar (state) {
      return state.snackbar
    }
  }
});
