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

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

import {
  ReadAllByInfraVendor,
  ReadAllByInfraVendorSuccess,
  ReadAllByInfraVendorFailure,
  ActionType,
} from './meta-vendor-crawler.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private metaVendorCrawlerService: MetaVendorCrawlerService,
  ) { }

  @Effect()
  readAllByInfraVendor$ = this.actions$.pipe(
    ofType(ActionType.ReadAllByInfraVendor),
    map((action: ReadAllByInfraVendor) => action.payload),
    exhaustMap((metaInfraVendor: MetaInfraVendor) =>
      this.metaVendorCrawlerService
        .readAllByInfraVendor(metaInfraVendor)
        .pipe(
          map((result: MetaVendorCrawler[]) => {
            return new ReadAllByInfraVendorSuccess(result);
          }),
          catchError(error => of(new ReadAllByInfraVendorFailure(error)))
        )
    )
  );
}
