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

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

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

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaSensorItemService: MetaSensorItemService,
  ) { }

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