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 { DiscoveryStartInfo } from '@overflow/commons-typescript/model/discovery';
import { DiscoveryService } from '../../service/discovery.service';

import {
  Setting,
  SettingSuccess,
  SettingFailure,
  ActionType,
} from './setting.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private discoveryService: DiscoveryService,
    private router: Router
  ) { }

  @Effect()
  startDiscovery$: Observable<Action> = this.actions$
  .ofType(ActionType.Setting)
  .map((action: Setting) => action.payload)
  .switchMap(payload => this.discoveryService.start(payload))
  .map(discoveryStartInfo => {
    return new SettingSuccess(discoveryStartInfo);
  })
  .catch((error: RPCClientError) => {
    console.log(error.response.message);
    return of(new SettingFailure(error));
  });

}
