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 { Infra } from '@overflow/commons-typescript/model/infra';
import { InfraService } from '../../service/infra.service';

import {
  ReadAllByDomain,
  ReadAllByDomainSuccess,
  ReadAllByDomainFailure,
  ReadAllByProbe,
  ReadAllByProbeSuccess,
  ReadAllByProbeFailure,
  ActionType,
} from './list.action';
import { Domain } from '@overflow/commons-typescript/model/domain';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private infraService: InfraService,
    private router: Router
  ) { }

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

    @Effect()
    readAllByProbe$: Observable<Action> = this.actions$
      .ofType(ActionType.ReadAllByProbe)
      .map((action: ReadAllByProbe) => action.payload)
      .switchMap(payload => this.infraService.readAllByProbe(payload.probe, payload.pageParams))
      .map(page => {
        return new ReadAllByProbeSuccess(page);
      })
      .catch((error: RPCClientError) => {
        return of(new ReadAllByProbeFailure(error));
      });
}
