import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import * as actions from './task-articles.actions';
import { map, flatMap, catchError } from 'rxjs/operators';
import { EISPublicService, StrictHttpResponse, ResponseArgsOfIEnumerableOfArticleDTO } from '@swagger/eis';
import { of, NEVER } from 'rxjs';

@Injectable()
export class TaskArticlesEffects {
  constructor(private actions$: Actions, private eisPublicService: EISPublicService) {}

  getArticles$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.getArticles),
      map((action) => actions.getArticlesRequest({ taskId: action.taskId }))
    )
  );

  getArticlesRequest$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.getArticlesRequest),
      flatMap((action) =>
        this.eisPublicService
          .EISPublicGetArticlesResponse({
            infoId: action.taskId,
          })
          .pipe(
            catchError((err) => of<StrictHttpResponse<ResponseArgsOfIEnumerableOfArticleDTO>>(err)),
            map((response) => actions.getArticlesResponse({ taskId: action.taskId, response }))
          )
      )
    )
  );

  getArticlesResponse$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.getArticlesResponse),
      flatMap((action) => {
        if (action.response.ok) {
          return [
            actions.addArticles({
              taskId: action.taskId,
              articles: action.response.body.result.map((article) => ({
                ...article,
                taskId: action.taskId,
              })),
            }),
          ];
        }
        return NEVER;
      })
    )
  );
}
