import {Injectable} from '@angular/core';
import {Effect, Actions} from '@ngrx/effects';

import {AppState} from '../reducers';
import {CartActions} from '../actions';
import {EcmCartService} from '../../ecm-view/ecm-cart/ecm-cart.service';

@Injectable()
export class CartEffects {
    constructor (
        private update$: Actions,
        private cartActions: CartActions,
        private svc: EcmCartService,
    ) {}

    @Effect() loadCartItems$ = this.update$
        .ofType(CartActions.LOAD_CART_ITEMS)
        .switchMap(() => this.svc.fetchCartItems())
        .map(items => this.cartActions.loadCartItemsSuccess(items));

    @Effect() addToCart$ = this.update$
        .ofType(CartActions.ADD_TO_CART_SUCCESS)
        .map(action => action.payload)
        .switchMap(item => this.svc.addToCart(item));
    
    @Effect() updateCart$ = this.update$
        .ofType(CartActions.UPDATE_CART)
        .map(action => action.payload)
        .switchMap(item => this.svc.updateCart(item))
        .map(item => this.cartActions.updateCartSuccess(item));

    @Effect() deleteFromCart$ = this.update$
        .ofType(CartActions.DELETE_CART_ITEM)
        .map(action => action.payload)
        .switchMap(item => this.svc.deleteCartItem(item))
        .map(item => this.cartActions.deleteCartItemSuccess(item));
    
}
