import {handleActions} from 'redux-actions';

export function init() {
    return {
        loading:false
    };
}

export function clearItem(state) {
    delete state.item;
    delete state.isEdit;
    return {...state};
}

export function loading(state) {
    return {...state, loading: true}
}

export function fail(state, action) {
    return {...state, err: action.err, loading: false};
}

export function list(state, action) {
    return {...state, loading: false, items: action.result.list, total: action.result.total};
}

export function item(state, action) {
    return {...state, loading: false, item: action.result};
}

export function create(state, action) {
    return {...state, loading: false, item: {...action.data, ...action.result}}
}

export function editStart(state) {
    return {...state, isEdit: true}
}

export function edit(state, action) {
    return {...state, loading: false, item: {...state.item, ...action.data}}
}

export function editEnd(state) {
    return {...state, isEdit: false}
}

export function update(state, action) {
    if (state.items && state.items.length) {
        for(let i=0, len = state.items.length; i<len;i++){
            if( state.items[i].id ==  action.data.id){
                state.items[i] = {... state.items[i], ...action.data, ...action.result};
                break;
            }
        }
    }
    if(state.item){
        state.item = {...state.item, ...action.data, ...action.result};
    }

    return {...state, loading: false};
}

export function remove(state, action) {
    state.items = state.items.filter(item=>item.id != action.data.id);
    return {...state, loading: false, removed: action.data.id}
}


export default function (command, other) {
    return {
        ['INIT_' + command]: init,
        ['CLEAR_' + command + '_ITEM']: clearItem,
        ['FETCH_' + command + '_LIST']: loading,
        ['FETCH_' + command + '_LIST_SUCCESS']: list,
        ['FETCH_' + command + '_LIST_FAILED']: fail,
        ['FETCH_' + command]: loading,
        ['FETCH_' + command + '_SUCCESS']: item,
        ['FETCH_' + command + '_FAILED']: fail,
        ['CREATE_' + command]: loading,
        ['CREATE_' + command + '_SUCCESS']: create,
        ['CREATE_' + command + '_FAILED']: fail,
        ['EDIT_' + command + '_START']: editStart,
        ['EDIT_' + command + '_SUBMIT']: loading,
        ['EDIT_' + command + '_SUCCESS']: edit,
        ['EDIT_' + command + '_FAILED']: fail,
        ['EDIT_' + command + '_END']: editEnd,
        ['UPDATE_' + command ]: loading,
        ['UPDATE_' + command + '_SUCCESS']: update,
        ['UPDATE_' + command + '_FAILED']: fail,
        ['DELETE_' + command]: loading,
        ['DELETE_' + command + '_SUCCESS']: remove,
        ['DELETE_' + command + '_FAILED']: fail,
        ...other
    };
}
