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

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

import {
  ReadAllByCrawler,
  ReadAllByCrawlerSuccess,
  ReadAllByCrawlerFailure,

  ReadAllMapByCrawler,
  ReadAllMapByCrawlerSuccess,
  ReadAllMapByCrawlerFailure,

  ActionType,
} from './meta-sensor-item-key.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaSensorItemKeyService: MetaSensorItemKeyService,
  ) { }

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

  @Effect()
  readAllMapByCrawler$ = this.actions$.pipe(
    ofType(ActionType.ReadAllMapByCrawler),
    map((action: ReadAllMapByCrawler) => action.payload),
    exhaustMap((metaCrawler: MetaCrawler) =>
      this.metaSensorItemKeyService
        .readAllMapByCrawler(metaCrawler)
        .pipe(
          map((result: Map<number, MetaSensorItemKey>) => {
            return new ReadAllMapByCrawlerSuccess(result);
          }),
          catchError(error => of(new ReadAllMapByCrawlerFailure(error)))
        )
    )
  );

}
