import {login} from '../api/sessionsApi'
import {updateSources} from './sourcesActions'

export const loggingIn = () => {
  return {type: 'LOGGING_IN'}
}

export const loggedIn = (response) => {
  return {
    type: 'LOGGED_IN',
    payload: response.user.id
  }
}

export const loginError = (response) => {
  return {
    type: 'LOGIN_ERROR',
    payload: response.errors
  }
}

export const logOut = () => {
   return {type: 'LOG_OUT'}
}

export function loginUser(userDetails, history) {
  return function(dispatch) {
    dispatch(loggingIn())
    return login(userDetails).then(response => {
        if (response.token) {
          dispatch(loggedIn(response));
          dispatch(updateSources(response.sources, history));
          sessionStorage.setItem('jwt', response.token);
        } else {
          dispatch(loginError(response));
        }
      }).catch(error => {
        throw(error);
      });
  }
}


export function logOutUser() {
  return function(dispatch) {
    sessionStorage.removeItem('jwt')
    dispatch(logOut());
  }
}

@@ -595,18 +595,16 @@
 %7B%0A      
-  
 if (resp
@@ -617,18 +617,16 @@
 oken) %7B%0A
-  
         
@@ -655,34 +655,32 @@
 onse));%0A        
-  
 dispatch(updateS
@@ -723,18 +723,16 @@
         
- 
- 
 sessionS
@@ -776,18 +776,16 @@
 ;%0A      
-  
 %7D else %7B
@@ -789,26 +789,24 @@
 e %7B%0A        
- 
- 
 dispatch(log
@@ -821,26 +821,24 @@
 response));%0A
-  
       %7D%0A    

Clean up formatting