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

import {AppState} from '../reducers';
import {SavedCardAction} from '../actions';
import {UserCardService} from '../../user-card/ecm-user-card.service';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class SavedCardEffects {
    constructor (
        private update$: Actions,
        private savedCardActions: SavedCardAction,
        private svc: UserCardService,
    ) {}
 
    @Effect() loadCards$ = this.update$
        .ofType(SavedCardAction.LOAD_SAVED_CARDS)
        .switchMap(() => this.svc.fetchUserCards())
        .map(cards => this.savedCardActions.loadSavedCardsSuccess(cards));

    @Effect() addNewCards$ = this.update$
        .ofType(SavedCardAction.ADD_NEW_CARD)
        .map(action => action.payload)
//        .switchMap(item => this.svc.addToCart(item)
        .map(userCard => this.savedCardActions.addNewCardSuccess(userCard));
    
    @Effect() addToCaddNewCards$art$ = this.update$
        .ofType(SavedCardAction.ADD_NEW_CARD_SUCCESS)
        .map(action => action.payload)
        .switchMap(card => this.svc.addUserCard(card));
    
    @Effect() deleteCards$ = this.update$
        .ofType(SavedCardAction.DELETE_CARD_SUCCESS)
        .map(action => action.payload)
        .switchMap(card => this.svc.deleteUserCard(card))
        //.map(card => this.savedCardActions.deleteCardSuccess(card));
    
}
