import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { map, mergeMap, catchError } from 'rxjs/operators';

import {  SelectCustomerAction, SelectCustomerSuccessAction, SelectCustomerFailureAction, CustomerSaleActionTypes,
          LoadCustomerAction, LoadCustomerFailureAction, LoadCustomerSuccessAction} from '../actions/customer-sale.action';
import { of } from 'rxjs';
import { ShoppingService } from 'src/app/services/shopping.service';

@Injectable()
export class CustomerSaleEffects {

  constructor(
    private actions$: Actions,
    private shoppingService: ShoppingService
  ) { }


  @Effect() selectCustomer$ = this.actions$
    .pipe(
      ofType<SelectCustomerAction>(CustomerSaleActionTypes.SELECT_CUSTOMER),
      mergeMap(
        (data) => this.shoppingService.setCustomerSale(data.payload)
          .pipe(
            map((result) => new SelectCustomerSuccessAction(result)),
            catchError(error => of(new SelectCustomerFailureAction(error)))
          )
      )
    );


    @Effect() loadCustomer$ = this.actions$
    .pipe(
      ofType<LoadCustomerAction>(CustomerSaleActionTypes.LOAD_CUSTOMER),
      mergeMap(
        (_) => this.shoppingService.getCustomerSale()
          .pipe(
            map((result) => new LoadCustomerSuccessAction(result)),
            catchError(error => of(new LoadCustomerFailureAction(error)))
          )
      )
    );

}
