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

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

import { of } from 'rxjs';
import { map, catchError, switchMap, mergeMap } from 'rxjs/operators';

import {
  loadDashboards,
  loadDashboardsSuccess,
  loadDashboardsFailure,
  addDashboard,
  removeDashboard,
  removeDashboardSuccess,
  removeDashboardFailure
} from './action';
import { DashboardService } from '../service/dashboard.service';
import { Dashboard } from '../model/Dashboard';

@Injectable()
export class Effects {
  loadDashboards$ = createEffect(() =>
    this.actions$.pipe(
      ofType(loadDashboards),
      switchMap(() =>
        this.dashboardService.getDashboards().pipe(
          map((dashboards: Dashboard[]) =>
            loadDashboardsSuccess({ dashboards })
          ),
          catchError(error => of(loadDashboardsFailure({ error })))
        )
      )
    )
  );

  removeBookFromCollection$ = createEffect(() =>
    this.actions$.pipe(
      ofType(removeDashboard),
      mergeMap(({ id }) =>
        this.dashboardService.deleteDashboard(id).pipe(
          map(() => removeDashboardSuccess({ id })),
          catchError(error => of(removeDashboardFailure({ id, error })))
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private dashboardService: DashboardService
  ) {}
}
