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

import {Address} from '../../user-address/address-manager/address.model';
import {AdressAction} from '../actions';
import * as _ from 'lodash';

export type AddressState = Address[];

const initialState: AddressState = [];

export default function (state = initialState, action: Action): AddressState {
    switch (action.type){
        case AdressAction.LOAD_ADDRESS_SUCCESS: {
            return action.payload;
        }
        case AdressAction.ADD_NEW_ADDRESS_SUCCESS: {
            return [...state, action.payload];
        }
        case AdressAction.DELETE_ADDRESS_SUCCESS: {
            return state.filter(userAddress => {
                return userAddress.lineNo !== action.payload.lineNo;
            });
        }
        case AdressAction.UPDATE_ADDRESS_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;
        }
        default: {
            return state;
        }
    }
}