import { Injectable } from '@angular/core';

import { Actions, ofType, createEffect } from '@ngrx/effects';

import { of } from 'rxjs';
import { catchError, exhaustMap, map, tap } from 'rxjs/operators';

import { StatusCode } from '@ucap-webmessenger/api';

import { NGXLogger } from 'ngx-logger';

import { companyList, companyListSuccess, companyListFailure } from './actions';
import { ExternalApiService } from '@ucap-webmessenger/api-external';

@Injectable()
export class Effects {
  fetch$ = createEffect(() =>
    this.actions$.pipe(
      ofType(companyList),
      map(action => action),
      exhaustMap(req =>
        this.externalApiService.companyList(req).pipe(
          map(res => {
            if (res.statusCode === StatusCode.Success) {
              return companyListSuccess(res);
            } else {
              return companyListFailure({ error: 'Failed' });
            }
          }),
          catchError(error => of(companyListFailure({ error })))
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private externalApiService: ExternalApiService,
    private logger: NGXLogger
  ) {}
}
