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 { NGXLogger } from 'ngx-logger';

import {
  versionInfo2,
  versionInfo2Success,
  versionInfo2Failure
} from './actions';

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

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