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 { Probe } from '@overflow/commons-typescript/model/probe';
import { ProbeHostService } from '../../service/probe-host.service';

import {
  ReadByProbe,
  ReadByProbeSuccess,
  ReadByProbeFailure,
  ActionType
} from './probe-host.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private probeHostService: ProbeHostService,
    private router: Router
  ) { }

  @Effect()
  read$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadByProbe)
    .map((action: ReadByProbe) => action.payload)
    .switchMap(payload => this.probeHostService.readByProbe(payload))
    .map(probe => {
      return new ReadByProbeSuccess(probe);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadByProbeFailure(error));
    });
}
