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

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

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

import { PublicApiService } from '@ucap-webmessenger/api-public';
import { StatusCode } from '@ucap-webmessenger/api';
import { SessionStorageService } from '@ucap-webmessenger/web-storage';

import { fetch, fetchSuccess, fetchFailure } from './actions';

@Injectable()
export class Effects {
  fetch$ = createEffect(() =>
    this.actions$.pipe(
      ofType(fetch),
      map(action => action),
      exhaustMap(req =>
        this.publicApiService.versionInfo2(req).pipe(
          map(res => {
            if (res.statusCode === StatusCode.Success) {
              console.log('fetchSuccess', res);
              return fetchSuccess(res);
            } else {
              return fetchFailure({ error: 'Failed' });
            }
          }),
          catchError(error => of(fetchFailure({ error })))
        )
      )
    )
  );

  fetchSuccess$ = createEffect(
    () =>
      this.actions$.pipe(
        ofType(fetchSuccess),
        tap(params => {})
      ),
    { dispatch: false }
  );

  constructor(
    private actions$: Actions,
    private publicApiService: PublicApiService,
    private sessionStorageService: SessionStorageService,
    private router: Router
  ) {}
}
