import {handleActions} from 'redux-actions';
import base, {loading, fail} from './base';

let _user = sessionStorage.getItem('user');
try {
    _user = JSON.parse(_user);
    if (_user && Date.now() - _user.time < 24 * 3600000) {
        _user = _user.data;
    } else {
        _user = {};
    }
} catch (ex) {
    _user = {};
}

const initState = {
    ..._user,
    loading: false,
};

export default handleActions(base('USER', {
    INIT_USER: function () {
        return {...initState};
    },
    LOGIN_REQUEST: loading,
    LOGIN_SUCCESS: function (state, action) {
        return {...state, loading: false, ...action.user};
    },
    LOGIN_ERROR: fail,
    LOGOUT: function (state) {
        return {...state, auth: {}, loading: false};
    },
    MODIFY_USER_PASSWORD: loading,
    MODIFY_USER_PASSWORD_SUCCESS: function (state) {
        return {...state, loading: false};
    },
    MODIFY_USER_PASSWORD_FAILED: fail,
}), {...initState});
