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

import { MetaSensorItemUnitService } from '../../../service/meta-sensor-item-unit.service';

import {
  ReadAll,
  ReadAllSuccess,
  ReadAllFailure,
  ActionType,
} from './meta-sensor-item-unit.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaSensorItemUnitService: MetaSensorItemUnitService,
  ) { }

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