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

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

import {
  ReadAllByCrawler,
  ReadAllByCrawlerSuccess,
  ReadAllByCrawlerFailure,
  ActionType,
} from './meta-sensor-display-item.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaSensorDisplayItemService: MetaSensorDisplayItemService,
  ) { }

  @Effect()
  readAllByCrawler$ = this.actions$.pipe(
    ofType(ActionType.ReadAllByCrawler),
    map((action: ReadAllByCrawler) => action.payload),
    exhaustMap((metaCrawler: MetaCrawler) =>
      this.metaSensorDisplayItemService
        .readAllByCrawler(metaCrawler)
        .pipe(
          map((result: MetaSensorDisplayItem[]) => {
            return new ReadAllByCrawlerSuccess(result);
          }),
          catchError(error => of(new ReadAllByCrawlerFailure(error)))
        )
    )
  );
}
