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

import { Effect, Actions, ofType } from '@ngrx/effects';
import { Action } from '@ngrx/store';

import { of } from 'rxjs';
import { catchError, exhaustMap, map, tap } from 'rxjs/operators';

import { RPCClientError } from '@loafer/ng-rpc';

import { Domain } from '@overflow/commons-typescript/model/domain';

import {
  ReadAllByMember,
  ReadAllByMemberSuccess,
  ReadAllByMemberFailure,
  MarkAllAsRead,
  MarkAllAsReadSuccess,
  MarkAllAsReadFailure,
  ActionType,
} from './notification.action';
import { NotificationService } from '../../../service/notification.service';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private notificationService: NotificationService,
    private router: Router
  ) { }

  @Effect()
  readAllByMember$ = this.actions$.pipe(
    ofType(ActionType.ReadAllByMember),
    map((action: ReadAllByMember) => action.payload),
    exhaustMap(payload =>
      this.notificationService
        .readAllByMemberEmail(payload.member.email, payload.pageParams)
        .pipe(
          map(page => {
            return new ReadAllByMemberSuccess(page);
          }),
          catchError(error => of(new ReadAllByMemberFailure(error)))
        )
    )
  );

  @Effect()
  markAllAsRead$ = this.actions$.pipe(
    ofType(ActionType.MarkAllAsRead),
    map((action: MarkAllAsRead) => action.payload),
    exhaustMap(payload =>
      this.notificationService
        .markAllAsReadByMemberEmail(payload.member.email, payload.pageParams)
        .pipe(
          map(page => {
            return new MarkAllAsReadSuccess(page);
          }),
          catchError(error => of(new MarkAllAsReadFailure(error)))
        )
    )
  );

}
