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

import router from './route';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: 'Kittisak Maneewong',
    user: {
      name: null,
      email: null
    },
    jwt: localStorage.getItem('access_token') || null,
    jwt_employer: localStorage.getItem('access_token_employer') || null,
    dialog: false,
    snackbar: {
      show: false,
      color: null,
      text: null
    },
    loading: false,
    error: 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
    },
    setUser (state, payload) {
      state.user = payload
    },
    setLoading (state, payload) {
      state.loading = payload
    },
    setError (state, payload) {
      state.error = payload
    }
  },
  actions: {
    login ({commit, dispatch}, payload) {
      return new Promise((resolve, reject) => {
        commit('setLoading', true)
        axios.post('api/auth/login', payload)
        .then(res => {
          commit('setLoading', false)
          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)
          }
          dispatch('checkUser')
          commit('setSnackbar', {
            show: true,
            color: 'success',
            text: 'เข้าสู่ระบบสำเร็จ!'
          })
          commit('setDialog', false)
          resolve(res)
          console.log(res)
        })
        .catch(err => {
          commit('setLoading', false)
          if (err.response.data.error === 'invalid_credentials') {
            commit('setError', 'ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง')
            setTimeout(() => {
              commit('setError', null)
            }, 4000);
          }
          console.log(err.response)
          reject(err.response)
        })
      })
    },
    register ({commit}, payload) {
      return new Promise((resolve, reject) => {
        commit('setLoading', true)
        axios.post('api/auth/register', payload)
          .then(res => {
            commit('setLoading', false)
            commit('setSnackbar', {
              show: true,
              color: 'success',
              text: 'ลงทะเบียนสำเร็จ!'
            })
            commit('setDialog', false)
            console.log(res)
            resolve(res)
          })
          .catch(err => {
            commit('setLoading', false)
            console.log(err.response)
            if (err.response.data == '{"email":["The email has already been taken."]}') {
              commit('setError', 'อีเมลล์นี้ถูกใช้งานเเล้ว')
              setTimeout(() => {
                commit('setError', null)
              }, 4000);
            }
            reject(err.response)
          })
      })
    },
    logout ({commit}) {
      localStorage.removeItem('access_token')
      commit('setUser', {
        name: null,
        email: null
      })
      commit('setSnackbar', {
        show: true,
        color: 'success',
        text: 'ออกจากระบบสำเร็จ!'
      })
    },
    checkUser ({commit}) {
      if (!!localStorage.getItem('access_token')) {
        axios.get('/api/auth/current', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('access_token')}`
          }
        })
          .then(res => {
            commit('setUser', {
              name: res.data.user.name,
              email: res.data.user.email_users
            })
            console.log(res)
          })
          .catch(err => {
            console.log(err.response)
          })
      }
    }
  },
  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
    },
    getUser (state) {
      return state.user
    },
    getLoading (state) {
      return state.loading
    },
    getError (state) {
      return state.error
    }
  }
});
