import { REST } from 'vuejs/api/rest-axios'
import { JSONAPI } from 'vuejs/api/json-axios'
import qs from 'querystring'

export default {
  namespaced: true,

  // initial state
  state : {
    uid:null,
    // username: '',
    mail:'',
    token: null,
    logout_token: null,
    isloggedin: false,
    isAdmin: false,
    canSearch: false
  },

  // getters
  getters : {},

  // mutations
  mutations : {
    setToken (state, data) {
      state.uid = data.current_user.uid
      // state.username = data.username
      state.mail = data.current_user.mail
      state.token = data.csrf_token
      state.isloggedin = true
      state.logout_token = data.logout_token
    },
    setUid (state, uid) {
      state.uid = uid
      state.isloggedin = true
    },
    setUser (state, data) {
      state.mail = data.mail[0].value
      state.uuid = data.uuid[0].value
    },
    setRoles (state, roles) {
      console.log("User setRoles", roles);
      state.roles = []
      for (var i = 0; i < roles.length; i++) {
        state.roles.push(roles[i].target_id)
      }
      // check if admin
      if(state.roles.indexOf('admin') != -1 || state.roles.indexOf('root') != -1){
        // console.log('is admin');
        state.isAdmin = true
      }
      // check if has access to search
      if(state.roles.indexOf('adherent') != -1){
        // console.log('is admin');
        state.canSearch = true
      }
    },
    setLoggedOut (state) {
      console.log("setLoggedOut state", state);
      state.uid= null
      state.mail = ''
      state.token = null
      state.isloggedin = false
      state.logout_token = null
      if (state.isAdmin){

        window.location.reload(true);
      }
      state.asAdmin = false
      state.canSearch = false
    }
  },

  // actions
  actions : {
    userLogin({ dispatch, commit, state }, credentials){
      dispatch('getToken', credentials)
        .then(() => {
          dispatch('getUser').then((userdata) => {
            console.log('User Loggedin');
            if (state.isAdmin){
              window.location.reload(true);
            }
          })
        })
    },
    getToken ({ dispatch, commit, state }, credentials) {
      return REST.post('/user/login?_format=json', credentials)
        .then(({ data }) => {
          console.log('user REST getToken data', data)
          commit('setToken', data)
        })
        .catch(( error ) => {
          console.warn('Issue with getToken', error)
          Promise.reject(error)
        })
    },
    getUser ({ dispatch, commit, state }) {
      let params = {
        token: state.token
      }
      return REST.get(`/user/${state.uid}?_format=json`, params)
        .then(({ data }) => {
          console.log('user REST getUser data', data)
          console.log('roles', data['roles'])
          commit('setUser', data)
          if(data.roles){
            commit('setRoles', data.roles)
          }
        })
        .catch(( error ) => {
            console.warn('Issue with getUser', error)
            Promise.reject(error)
        })
    },
    userLogout ({ commit, state }) {
      let credentials = qs.stringify({
        token: state.token
      })
      REST.post('/user/logout', credentials)
        .then((resp) => {
          console.log('userLogout resp', resp)
          commit('setLoggedOut')
        })
        .catch(( error ) => {
            console.warn('Issue with logout', error)
            Promise.reject(error)
        })
    }
  }

}
