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

import {AppState} from '../reducers';
import {OrderActions} from '../actions';
import {EcmOrderService} from '../../ecm-order/ecm-order.service';

@Injectable()
export class  OrderEffects {
    constructor (
        private update$: Actions,
        private orderActions: OrderActions,
        private svc: EcmOrderService,
    ) {}

    @Effect() loadOrderItems$ = this.update$
    .ofType(OrderActions.LOAD_ORDER_ITEMS)
    .switchMap(() => this.svc.fetchOrder())
    .map(orderItem => this.orderActions.loadOrderItemsSuccess(orderItem));
    
    @Effect() addNewOrder$ = this.update$
    .ofType(OrderActions.ADD_NEW_ORDER)
    .map(action => action.payload)
//     .switchMap(item => this.svc.addToCart(item)
      .map(orderItem => this.orderActions.addNewOrderSuccess(orderItem));
    
    @Effect() addToOrdNewOrders$art$ = this.update$
    .ofType(OrderActions.ADD_NEW_ORDER_SUCCESS)
    .map(action => action.payload)
    .switchMap(orderItem => this.svc.addToOrder(orderItem));
    
    @Effect() updateOrder$ = this.update$
        .ofType(OrderActions.UPDATE_ORDER)
        .map(action => action.payload)
        .switchMap(orderItem => this.svc.updateOrder(orderItem));
//        .map(item => this.orderActions.updateOrderoSuccess(item));
    
    @Effect() deleteOrders$ = this.update$
    .ofType(OrderActions.DELETE_ORDER_SUCCESS)
    .map(action => action.payload)
    .switchMap(orderItem => this.svc.cancelOrder(orderItem))
    //.map(card => this.savedCardActions.deleteCardSuccess(card));
    
//    @Effect() trackOrder$ = this.update$
//    .ofType(OrderActions.TRACK_ORDER_ITEM)
//    .map(action => action.payload)
//    .switchMap(item => this.svc.trackOrderItem(item))
//    .map(item => this.orderActions.trackOrderItemSuccess(item));
    
}
