import { decode as atob } from 'base-64'


export function authReducer(state, action){
    
  if(state === undefined){
    if (localStorage.authToken) {
      action.token = localStorage.authToken
      action.type = 'LOGIN'
    }
  else {
      return {}
      }
  }
  if (action.type === 'LOGIN' && action.token !== null)  {

    console.log('ЛОГИН')
    localStorage.authToken = action.token
    return {
        token: action.token, payload: JSON.parse(atob(action.token.split(".")[1])).sub
      }
  } 
  
  if (action.type === 'LOGOUT'){
    console.log('ЛОГАУТ')
    localStorage.removeItem("authToken") 
    return {}
  }
  return state
}

export default authReducer;