export default {
  namespaced: true,
  state: {
    user: undefined,
    permissions: null,
    roles: null,
    routesConfig: null
  },
  getters: {
    user: state => {
      if (!state.user) {
        try {
          const user = localStorage.getItem(process.env.VUE_APP_USER_KEY)
          if(user!='undefined'){
            state.user = JSON.parse(user)
          }          
        } catch (e) {
          console.error(e)
        }
      }
      return state.user
    },
    permissions: state => {
      //console.info('permissions',state.permissions)
      if (!state.permissions) {
        try {
          const permissions = localStorage.getItem(process.env.VUE_APP_PERMISSIONS_KEY)
          console.info('localStorage permissions',permissions)
          if(permissions!='undefined'){
            //console.info('permissions!=undefined',permissions!=undefined)
            state.permissions = JSON.parse(permissions)
            state.permissions = state.permissions ? state.permissions : []
          }
          else{
            //console.info('permissions 1 []')
            state.permissions=[]
          }
          
        } catch (e) {
          console.error(e.message)
        }
      }
      return state.permissions
    },
    roles: state => {
      if (!state.roles) {
        try {
          const roles = localStorage.getItem(process.env.VUE_APP_ROLES_KEY)
          if(roles!='undefined'){
            state.roles = JSON.parse(roles)
            state.roles = state.roles ? state.roles : []
          }
          else{
            state.roles=[]
          }          
          
        } catch (e) {
          console.error(e.message)
        }
      }
      return state.roles
    },
    routesConfig: state => {
      if (!state.routesConfig) {
        try {
          const routesConfig = localStorage.getItem(process.env.VUE_APP_ROUTES_KEY)
          if(routesConfig!='undefined'){
            state.routesConfig = JSON.parse(routesConfig)
            state.routesConfig = state.routesConfig ? state.routesConfig : []
          }
          else{
            state.routesConfig=[]
          }
        } catch (e) {
          console.error(e.message)
        }
      }
      return state.routesConfig
    }
  },
  mutations: {
    setUser (state, user) {
      state.user = user
      localStorage.setItem(process.env.VUE_APP_USER_KEY, JSON.stringify(user))
    },
    setPermissions(state, permissions) {
      state.permissions = permissions
      localStorage.setItem(process.env.VUE_APP_PERMISSIONS_KEY, JSON.stringify(permissions))
    },
    setRoles(state, roles) {
      state.roles = roles
      localStorage.setItem(process.env.VUE_APP_ROLES_KEY, JSON.stringify(roles))
    },
    setRoutesConfig(state, routesConfig) {
      state.routesConfig = routesConfig
      localStorage.setItem(process.env.VUE_APP_ROUTES_KEY, JSON.stringify(routesConfig))
    }
  }
}
