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

import { MetaInfraVendor, MetaInfraType } from '@overflow/commons-typescript/model/meta';

import { MetaInfraVendorService } from '../../../service/meta-infra-vendor.service';

import {
  ReadAllByMetaInfraType,
  ReadAllByMetaInfraTypeSuccess,
  ReadAllByMetaInfraTypeFailure,
  ActionType,
} from './meta-infra-vendor.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaInfraVendorService: MetaInfraVendorService,
  ) { }

  @Effect()
  readAllByMetaInfraType$ = this.actions$.pipe(
    ofType(ActionType.ReadAllByMetaInfraType),
    map((action: ReadAllByMetaInfraType) => action.payload),
    exhaustMap((metaInfraType: MetaInfraType) =>
      this.metaInfraVendorService
        .readAllByMetaInfraType(metaInfraType)
        .pipe(
          map((result: MetaInfraVendor[]) => {
            return new ReadAllByMetaInfraTypeSuccess(result);
          }),
          catchError(error => of(new ReadAllByMetaInfraTypeFailure(error)))
        )
    )
  );
}
