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 { MetaProbeArchitecture } from '@overflow/commons-typescript/model/meta';

import { MetaProbeArchitectureService } from '../../../service/meta-probe-architecture.service';

import {
  ReadAll,
  ReadAllSuccess,
  ReadAllFailure,
  ActionType,
} from './meta-probe-architecture.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaProbeArchitectureService: MetaProbeArchitectureService,
  ) { }

  @Effect()
  readAll$ = this.actions$.pipe(
    ofType(ActionType.ReadAll),
    exhaustMap(() =>
      this.metaProbeArchitectureService
        .readAll()
        .pipe(
          map((result: MetaProbeArchitecture[]) => {
            return new ReadAllSuccess(result);
          }),
          catchError(error => of(new ReadAllFailure(error)))
        )
    )
  );
}
