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 { Sensor } from '@overflow/commons-typescript/model/sensor';
import { SensorService } from '../../service/sensor.service';

import {
  ReadAllByDomain,
  ReadAllByDomainSuccess,
  ReadAllByDomainFailure,
  ReadAllByInfra,
  ReadAllByInfraSuccess,
  ReadAllByInfraFailure,
  ReadAllByTarget,
  ReadAllByTargetSuccess,
  ReadAllByTargetFailure,
  ActionType,
} from './list.action';

@Injectable()
export class Effects {

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

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

  @Effect()
  readAllByInfra$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByInfra)
    .map((action: ReadAllByInfra) => action.payload)
    .switchMap(payload => this.service.readAllByInfra(payload.id, payload.pageParams))
    .map(list => {
      return new ReadAllByInfraSuccess(list);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByInfraFailure(error));
    });

  @Effect()
  readAllByTarget$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByTarget)
    .map((action: ReadAllByTarget) => action.payload)
    .switchMap(payload => this.service.readAllByTarget(payload.target, payload.pageParams))
    .map(list => {
      return new ReadAllByTargetSuccess(list);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByTargetFailure(error));
    });
}
