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

import { MetaInfraTypeService } from '../../../service/meta-infra-type.service';

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

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaInfraTypeService: MetaInfraTypeService,
  ) { }

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