import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import { Effect, Actions, ofType } from '@ngrx/effects';
import { catchError, exhaustMap, map, tap } from 'rxjs/operators';

import { MetaCrawler } from '@overflow/commons-typescript/model/meta';

import { MetaCrawlerService } from '../../../service/meta-crawler.service';

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

import {
  MetaCrawlerEntitySelector,
} from '../../';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaCrawlerService: MetaCrawlerService,
  ) { }

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