import { UpdateUserPreferences } from './../../core/actions';
import { GlobalState } from '@app/core/state';
import { Store } from '@ngrx/store';
import { forkJoinWithKeys } from '@app/degree-planner/shared/utils';
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { DarsActionTypes } from '@app/dars/store/actions';
import * as darsActions from '@app/dars/store/actions';
import { flatMap, map } from 'rxjs/operators';
import { DarsApiService } from '../services/api.service';
import { Alert, DarsDisclaimerAlert } from '@app/core/models/alert';
import { DegreePlannerApiService } from '@app/degree-planner/services/api.service';

@Injectable()
export class DARSEffects {
  constructor(
    private actions$: Actions,
    private api: DarsApiService,
    private degreeAPI: DegreePlannerApiService,
    private store$: Store<GlobalState>,
  ) {}

  @Effect()
  load$ = this.actions$.pipe(
    ofType(DarsActionTypes.StartLoadingMetadata),

    flatMap(() => {
      return forkJoinWithKeys({
        metadata: this.api.getAudits(),
        userPreferences: this.degreeAPI.getUserPreferences(),
      });
    }),

    map(({ metadata, userPreferences }) => {
      const alerts: Alert[] = [];
      if (userPreferences.darsHasDismissedDisclaimer !== true) {
        alerts.push(
          new DarsDisclaimerAlert(() => {
            this.store$.dispatch(
              new UpdateUserPreferences({
                darsHasDismissedDisclaimer: true,
              }),
            );
          }),
        );
      }

      return new darsActions.AddAuditMetadata({ metadata });
    }),
  );

  @Effect()
  getAudit$ = this.actions$.pipe(
    ofType(DarsActionTypes.StartLoadingAudit),
    flatMap((action: darsActions.StartLoadingAudit) => {
      const metadata = action.payload;
      return this.api.getAudit(metadata.darsDegreeAuditReportId).pipe(
        map(audit => {
          return new darsActions.DoneLoadingAudit({ metadata, audit });
        }),
      );
    }),
  );
}