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/switchMap';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';

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

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

import { NoAuthProbe } from '@overflow/commons-typescript/model/noauth';
import { NoAuthProbeService } from '../../service/noauth-probe.service';

import {
  ReadAllByDomain,
  ReadAllByDomainFailure,
  ReadAllByDomainSuccess,
  Accept,
  AcceptSuccess,
  AcceptFailure,
  Deny,
  DenySuccess,
  DenyFailure,
  ActionType,
} from './noauth-probe.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private noAuthProbeService: NoAuthProbeService,
    private router: Router
  ) { }

  @Effect()
  readAllByDomain$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByDomain)
    .map((action: ReadAllByDomain) => action.payload)
    .switchMap(payload => this.noAuthProbeService.readAllByDomain(payload))
    .map(noAuthProbes => {
      return new ReadAllByDomainSuccess(noAuthProbes);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByDomainFailure(error));
    });

  @Effect()
  accept$: Observable<Action> = this.actions$
    .ofType(ActionType.Accept)
    .map((action: Accept) => action.payload)
    .switchMap(payload => this.noAuthProbeService.acceptNoAuthProbe(payload))
    .map(noAuthProbes => {
      return new AcceptSuccess(noAuthProbes);
    })
    .catch((error: RPCClientError) => {
      return of(new AcceptFailure(error));
    });

  @Effect()
  deny$: Observable<Action> = this.actions$
    .ofType(ActionType.Deny)
    .map((action: Deny) => action.payload)
    .switchMap(payload => this.noAuthProbeService.denyNoauthProbe(payload))
    .map(noAuthProbes => {
      return new DenySuccess(noAuthProbes);
    })
    .catch((error: RPCClientError) => {
      return of(new DenyFailure(error));
    });

}
