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

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    message: 'Kittisak Maneewong',
    user: {
      name: null,
      email: null
    },
    employer: {
      id: null,
      username: null,
      company_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,
    time: {
      date: '',
      time: ''
    }
  },
  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
    },
    setEmployer (state, payload) {
      state.employer = payload
    },
    setLoading (state, payload) {
      state.loading = payload
    },
    setError (state, payload) {
      state.error = payload
    },
    setTime (state, payload) {
      state.time = 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) {
            iView.LoadingBar.finish()
            localStorage.setItem('access_token', res.data.token)
            commit('setJwt', res.data.token)
            dispatch('checkUser')
          } else {
            localStorage.setItem('access_token_employer', res.data.token)
            commit('setJwtEmployer', res.data.token)
            dispatch('checkEmployer')
          }
          commit('setSnackbar', {
            show: true,
            color: 'success',
            text: 'เข้าสู่ระบบสำเร็จ!'
          })
          commit('setDialog', false)
          resolve(res)
          console.log(res)
        })
        .catch(err => {
          iView.LoadingBar.error()
          commit('setLoading', false)
          if (err.response.data.error === 'invalid_credentials') {
            if (payload.role === 1) {
              commit('setError', 'อีเมลหรือรหัสผ่านไม่ถูกต้อง')
            } else {
              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 => {
            if (payload.role === 1) {
              iView.LoadingBar.finish()
            }
            commit('setLoading', false)
            commit('setSnackbar', {
              show: true,
              color: 'success',
              text: 'ลงทะเบียนสำเร็จ!'
            })
            commit('setDialog', false)
            console.log(res)
            resolve(res)
          })
          .catch(err => {
            iView.LoadingBar.error()
            commit('setLoading', false)
            console.log(err.response)
            const error = JSON.parse(err.response.data);
            if (error.username && error.email) {
              commit('setError', 'ชื่อผู้ใช้เเละอีเมลถูกใช้งานเเล้ว')
              setTimeout(() => {
                commit('setError', null)
              }, 4000);
            } else if (error.email) {
              commit('setError', 'อีเมลนี้ถูกใช้งานเเล้ว')
              setTimeout(() => {
                commit('setError', null)
              }, 4000);
              errorMessage = 'อีเมลนี้ถูกใช้งานเเล้ว'
            } else if (error.username) {
              commit('setError', 'ชื่อผู้ใช้นี้ถูกใช้งานเเล้ว')
              setTimeout(() => {
                commit('setError', null)
              }, 4000);
              errorMessage = 'ชื่อผู้ใช้นี้ถูกใช้งานเเล้ว'
            }
            reject(err.response)
          })
      })
    },
    logout ({commit}) {
      iView.LoadingBar.finish()
      localStorage.removeItem('access_token')
      commit('setUser', {
        name: null,
        email: null
      })
      commit('setSnackbar', {
        show: true,
        color: 'success',
        text: 'ออกจากระบบสำเร็จ!'
      })
    },
    logoutEmployer ({commit}) {
      localStorage.removeItem('access_token_employer')
      commit('setEmployer', {
        username: null,
        company_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)
          })
      }
    },
    checkEmployer ({commit}) {
      return new Promise((resolve, reject) => {
        if (!!localStorage.getItem('access_token_employer')) {
          axios.get('/api/auth/current', {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('access_token_employer')}`
            }
          })
            .then(res => {
              resolve(res.data.user)
              commit('setEmployer', {
                id: res.data.user.id,
                username: res.data.user.username,
                company_name: res.data.user.company_name,
                email: res.data.user.email_employers
              })
              // commit('setTime', res.headers.date)
              const a = res.headers.date.split(',')[1].split(' ')
              const date = a[1] + ' ' + a[2] + ' ' +a[3]
              const b = res.headers.date.split(',')[1].split(' ')[4].split(':')
              const time =  ((b[0]*1 + 7) % 24) +':'+b[1]+':'+b[2]
              commit('setTime', {
                date: date,
                time: time
              })
            })
            .catch(err => {
              console.log(err.response)
              if (err.response.data.message === 'Token has expired') {
                localStorage.removeItem('access_token_employer')
              }
              reject(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
    },
    getEmployer (state) {
      return state.employer
    },
    getLoading (state) {
      return state.loading
    },
    getError (state) {
      return state.error
    },
    getTime (state) {
      return state.time
    }
  }
});
