import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import * as actions from './history.actions';
import { switchMap, map, catchError, flatMap } from 'rxjs/operators';
import { OrderService, StrictHttpResponse, ResponseArgsOfHistoryDTO, HistoryDTO } from '@swagger/oms';
import { of } from 'rxjs';
import { OrderHistoryStatus } from '../defs';

@Injectable({ providedIn: 'root' })
export class HistoryEffects {
  constructor(private actions$: Actions, private orderService: OrderService) {}

  initHistory$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.initOrderHistory),
      map((action) => actions.fetchHistory({ id: action.id }))
    )
  );

  fetchHistory$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.fetchHistory),
      switchMap((action) =>
        this.orderService
          .OrderGetOrderItemStatusHistoryResponse({
            orderItemSubsetId: action.id,
          })
          .pipe(
            catchError((err) => of<StrictHttpResponse<ResponseArgsOfHistoryDTO>>(err)),
            map((response: StrictHttpResponse<ResponseArgsOfHistoryDTO>) =>
              actions.fetchHistoryDone({
                id: action.id,
                response,
              })
            )
          )
      )
    )
  );

  fetchHistoryDone$ = createEffect(() =>
    this.actions$.pipe(
      ofType(actions.fetchHistoryDone),
      flatMap((action) => {
        if (action.response.ok) {
          const histories = (action.response.body.result as unknown) as HistoryDTO[];
          return [
            actions.addOrderHistory({
              id: action.id,
              histories,
            }),
          ];
        }

        return [
          actions.setStatus({
            id: action.id,
            status: OrderHistoryStatus.ERROR,
          }),
        ];
      })
    )
  );
}
