import {handleActions} from 'redux-actions';
import {combineReducer} from 'redux';

let _user = sessionStorage.getItem('user');
try {
    _user = JSON.parse(_user);
} catch (ex) {
    _user = {};
}

const user = handleActions({
    ['LOGIN_REQUEST'](state) {
        return {...state, loading: true};
    },
    ['LOGIN_SUCCESS'](state, action) {
        sessionStorage.setItem('user', JSON.stringify(action.user));
        return {...state, loading: false, ...action.user};
    },
    ['LOGIN_ERROR'](state, action) {
        return {...state, err: action.err, loading: false};
    },
    ['LOGOUT'](state) {
        return {...state, auth: {}, loading: false};
    },

    ['CREATE_USER_ITEM'](state){
        return {...state, loading: true};
    },
    ['CREATE_USER_ITEM_SUCCESS'](state, action){
        return {...state, loading: false};
    },
    ['CREATE_USER_ITEM_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

    ['FETCH_USER_LIST'](state){
        return {...state, loading: true};
    },
    ['FETCH_USER_LIST_SUCCESS'](state, action){
        return {...state, loading: false, items: action.items, total: action.total};
    },
    ['FETCH_USER_LIST_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

    ['FETCH_USER_ITEM'](state){
        return {...state, loading:true};
    },
    ['FETCH_USER_ITEM_SUCCESS'](state, action){
        return {...state, loading: false, item: action.item};
    },
    ['FETCH_USER_ITEM_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

    ['UPDATE_USER_ITEM'](state){
        return {...state, loading:true};
    },
    ['UPDATE_USER_ITEM_SUCCESS'](state, action){
        return {...state, loading: false, item: {...state.item, ...action.item}};
    },
    ['UPDATE_USER_ITEM_FAILED'](state, action){
        return {...state, loading: false, err: action.err};
    },

}, {
    ..._user,
    loading: false,
});

export default user;
