import {Action} from '@ngrx/store';

import {ItemDetail} from '../../ecm-model/product-detail-model';
import {CartActions} from '../actions';
import * as _ from 'lodash';

export type CartListState = ItemDetail[];

const initialState: CartListState = [];

export default function (state = initialState, action: Action): CartListState {
    switch (action.type){
        case CartActions.LOAD_CART_ITEMS_SUCCESS: {
            return action.payload;
        }
        case CartActions.ADD_TO_CART_SUCCESS: {
            return [...state, action.payload];
        }
        case CartActions.DELETE_CART_ITEM_SUCCESS: {
            return state.filter(item => {
                return item.itemCode !== action.payload.itemCode;
            });
        }
        case CartActions.UPDATE_CART_SUCCESS: {
            let index = _.findIndex(state, {itemCode: action.payload.itemCode});
            if (index >= 0) {
                return [
                    ...state.slice(0, index),
                    action.payload,
                    ...state.slice(index + 1)
                ];
            }
            return state;
        }
        case CartActions.RESET_CART: {
            return initialState;
        }
        default: {
            return state;
        }
    }
}