import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    url_api: 'https://smart.sportalsolerpalau.mx/QA/',
    status: '',
    token: localStorage.getItem('access_token') || '',
    user: {
      name: localStorage.getItem('user') || '',
      role: localStorage.getItem('role') || '',
      id: localStorage.getItem('id') || ''
    },
    permisos: {
      datos: localStorage.getItem('permisos') || [],
      error: false,
      mensaje: ''
    },
    msg: '',

  },
  mutations: {
    auth_request(state) {
      state.status = 'loading'
    },
    auth_success(state, token) {
      state.status = (token.response) ? 'Success' : 'Error'
      state.token = token.token
      state.user.name = token.userName
      state.user.role = token.role
      state.user.id = token.id
    },
    auth_error(state, msg) {
      state.status = 'error'
      state.msg = msg
    },
    logout(state) {
      state.status = ''
      state.token = ''
      state.user.name = ''
      state.user.role = ''
      state.user.id = '',
      state.permisos = {
        datos: [],
        error: false,
        mensaje: ''
      }
    },
    get_permisos(state, permiso) {
      state.permisos.datos = permiso.permisosDatos;
      state.permisos.error = permiso.error;
      state.permisos.mensaje = permiso.msg;

    }
  },
  actions: {
    getPermisos({ commit, state }, id) {
      return new Promise((resolve, reject) => {
        const token = localStorage.getItem('access_token')
        if (token) {
          var config_header = {
            headers: {
              Authorization: 'Bearer ' + token
            }
          }
        }
        axios.get(
          state.url_api + 'api/v1/quiosco/usuario/permiso/' +  state.user.id,
          config_header,
        )
          .then(response => {
            if (response.data.response) {
              let permisosDatos =  response.data.result;
              let error = false;
              let msg = "Permisos obtenidos correctamente";
              localStorage.setItem('permisos', permisosDatos )

              commit('get_permisos', { permisosDatos, error, msg })
              resolve(response)

            } else {
              var permisosDatos = []
              var error = true;
              var msg = "Los permisos no se obtuvieron de la forma esperada."
              commit('get_permisos', { permisosDatos, error, msg })
              resolve(response)
            }
          })
          .catch(error => {
            if (!error.status) {
              var permisosDatos = [];
              var error = true
              var msg = "Whoops, parece que tenemos problemas al obtener los permisos, Network error...";
              commit('get_permisos', { permisosDatos, error, msg })
              resolve(response)
            } else {
              this.strError = msjError;
            }
          });
      }) // end promise
    },
    login({ commit, state, dispatch }, user) {
      return new Promise((resolve, reject) => {
        commit('auth_request')
        axios({
          url: state.url_api + 'api/v1/login',
          data: user,
          method: 'POST'
        })
          .then(resp => {
            const response = resp.data.response
            const msg = resp.data.message
            if (response) {
              const token = resp.data.result['access_token']
              const userName = resp.data.result['user']
              const role = (resp.data.result['role'] === 'COLABORADOR') ? 'colaborador' : 'admin'
              const id = resp.data.result['dinum']

              localStorage.setItem('access_token', token)
              localStorage.setItem('user', userName)
              localStorage.setItem('role', role)
              localStorage.setItem('id', id)
              commit('auth_success', { token, userName, role, id, response })
              // Obtenemos permisos del usuario
              store.dispatch('getPermisos')
              resolve(response)
            } else {
              reject(response)
              commit('auth_error', msg)
            }
          })
          .catch(err => {
            reject(err)
            commit('auth_error', { err })
            localStorage.removeItem('access_token')
            localStorage.removeItem('user')
            localStorage.removeItem('role')
            localStorage.removeItem('id')
          })
      })
    },
    logout({ commit }) {
      return new Promise(resolve => {
        commit('logout')
        localStorage.removeItem('access_token')
        localStorage.removeItem('user')
        localStorage.removeItem('role')
        localStorage.removeItem('id')
        localStorage.removeItem('permisos')
        resolve()
      })
    }
  },
  getters: {
    isLoggedIn: state => !!state.token,
    authStatus: state => state.status,
    msgResponse: state => state.msg,
    user: state => state.user,
    permisos: state => state.permisos.datos
  }
})

export default store
