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

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

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/exhaustMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';

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

import { Notification } from '@overflow/commons-typescript/model/notification';
import { NotificationService } from '../../service/notification.service';

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

@Injectable()
export class Effects {

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

  @Effect()
  readAllByMember$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByMember)
    .map((action: ReadAllByMember) => action.payload)
    .switchMap(payload => this.notificationService.readAllByMember(payload.member, payload.pageParams))
    .map(page => {
      return new ReadAllByMemberSuccess(page);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByMemberFailure(error));
    });

    @Effect()
    markAllAsRead$: Observable<Action> = this.actions$
      .ofType(ActionType.MarkAllAsRead)
      .map((action: MarkAllAsRead) => action.payload)
      .switchMap(payload => this.notificationService.markAllAsRead(payload.member, payload.pageParams))
      .map(page => {
        return new MarkAllAsReadSuccess(page);
      })
      .catch((error: RPCClientError) => {
        return of(new MarkAllAsReadFailure(error));
      });
}
