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

import {Order} from '../../ecm-model/order-model';
import {OrderActions} from '../actions';
import * as _ from 'lodash';

export type OrderListState = Order[];

const initialState: OrderListState = [];

export default function (state = initialState, action: Action): OrderListState {
    switch (action.type){
        case OrderActions.LOAD_ORDER_ITEMS_SUCCESS: {
            console.log('reducer--payload',action.payload);
            return action.payload;
        }
        case OrderActions.ADD_NEW_ORDER_SUCCESS: {
            return [...state, action.payload];
        }
        case OrderActions.DELETE_ORDER_SUCCESS: {
            return state.filter(orderItem => {
              return orderItem.itemCode !== action.payload.itemCode;
          });
        }
//        case OrderActions.TRACK_ORDER_ITEM_SUCCESS: {
//            return state.filter(item => {
//                return item.itemCode !== action.payload.itemCode;
//            });
//        }
        case OrderActions.UPDATE_ORDER_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 OrderActions.RESET_ORDER: {
            return initialState;
        }
        default: {
            return state;
        }
    }
}
