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

import { MetaHistoryTypeService } from '../../../service/meta-history-type.service';

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

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaHistoryTypeService: MetaHistoryTypeService,
  ) { }

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