
import { Observable } from 'rxjs';
import userApi from '../api/user-api';
import { loginActionTypes as actionTypes } from './login-action-types';
import { authenticationSuccess, authenticationFailure, serverError, networkError } from './login-actions';

const loginEpic = (action$) => {
    return action$.ofType(actionTypes.FORM_SUBMISSION)
        .mergeMap(action => {
            const reqObservable = userApi.authenticate(action.username, action.password).share();

            const success = reqObservable.filter(res => !res.error).map(res => {
                sessionStorage.setItem('JWT_TOKEN', res.body.jwt);
                sessionStorage.setItem('USERNAME', action.username);
                const redirect = action.history.location.state ? action.history.location.state.from : '/';
                action.history.push(redirect);
                return authenticationSuccess();
            });
            const unauthorized = reqObservable.filter(res => res.unauthorized).map(authenticationFailure);
            const error = reqObservable.filter(res => res.error && !res.unauthorized).map(serverError);

            return success.merge(unauthorized, error).catch(val => Observable.of(networkError()) );
        });
};

export default loginEpic
