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

import {AppState} from '../reducers';
import {WishListActions} from '../actions';
import {EcmWishListService} from '../../ecm-view/ecm-wish-list/ecm-wish-list.service';

@Injectable()
export class WishlistEffects {
    constructor (
        private update$: Actions,
        private wishlistActions: WishListActions,
        private svc: EcmWishListService,
    ) {}

    @Effect() loadWishlistItems$ = this.update$
        .ofType(WishListActions.LOAD_WISHLIST_ITEMS)
        .switchMap(() => this.svc.fetchWishlistItems())
        .map(items => this.wishlistActions.loadWishlistItemsSuccess(items));

    @Effect() addToWishlist$ = this.update$
        .ofType(WishListActions.ADD_TO_WISHLIST_SUCCESS)
        .map(action => action.payload)
        .switchMap(item => this.svc.addToWishlist(item.itemCode));

    @Effect() deleteFromWishlist$ = this.update$
        .ofType(WishListActions.DELETE_WISHLIST_ITEM_SUCCESS)
        .map(action => action.payload)
        .switchMap(item => this.svc.deleteWishlistItem(item.itemCode));
}
