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

import {AppState} from '../reducers';
import {AdressAction} from '../actions';
import {UserAddressService} from '../../user-address/ecm-user-address.service';
import 'rxjs/add/operator/switchMap';

@Injectable()
export class AddressEffects {
    constructor (
        private update$: Actions,
        private addressActions: AdressAction,
       private svc: UserAddressService,
    ) {}

    @Effect() loadAddress$ = this.update$
        .ofType(AdressAction.LOAD_ADDRESS)
        .switchMap(() => this.svc.fetchUserAddress())
        .map(userAddresses => this.addressActions.loadAddressSuccess(userAddresses));

    @Effect() addNewAddress$ = this.update$
        .ofType(AdressAction.ADD_NEW_ADDRESS)
        .map(action => action.payload)
        .switchMap(userAddress => this.svc.addNewAddress(userAddress));
//        .map(userAddress => this.addressActions.addNewAddressSuccess(userAddress));
    
    @Effect() updateAddress$ = this.update$
        .ofType(AdressAction.UPDATE_ADDRESS)
        .map(action => action.payload)
       .switchMap(userAddress => this.svc.updateUserAddress(userAddress));
//        .map(userAddress => this.addressActions.updateAddressSuccess(userAddress));

    @Effect() deleteAddress$ = this.update$
        .ofType(AdressAction.DELETE_ADDRESS_SUCCESS)
        .map(action => action.payload)
        .switchMap(userAddress => this.svc.deleteUserAddress(userAddress));
//        .map(userAddress => this.addressActions.deleteAddressSuccess(userAddress));
    
}
