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 { DomainMember } from '@overflow/commons-typescript/model/domain';

import {
  ReadAllByCrawler,
  ReadAllByCrawlerSuccess,
  ReadAllByCrawlerFailure,
  ActionType,
} from './list.action';
import { MetaSensorDisplayItem } from '@overflow/commons-typescript/model/meta';
import { MetaSensorDisplayItemService } from '../../service/sensor-display-item.service';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private service: MetaSensorDisplayItemService,
    private router: Router
  ) { }

  @Effect()
  readAllByCrawler$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByCrawler)
    .map((action: ReadAllByCrawler) => action.payload)
    .switchMap(payload => this.service.readAllByMetaCrawler(payload))
    .map(list => {
      return new ReadAllByCrawlerSuccess(list);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByCrawlerFailure(error));
    });

}
