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

import { MetaInputTypeService } from '../../../service/meta-input-type.service';

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

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaInputTypeService: MetaInputTypeService,
  ) { }

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