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

import {
  ReadAllByDomainID,
  ReadAllByDomainIDFailure,
  ReadAllByDomainIDSuccess,
  Read,
  ReadSuccess,
  ReadFailure,
  Modify,
  ModifySuccess,
  ModifyFailure,
  ActionType
} from './probe.action';
import { ProbeHostService } from '../../../service/probe-host.service';
import { ProbeService } from '../../../service/probe.service';

@Injectable()
export class Effects {

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

  @Effect()
  ReadAllByDomainID$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByDomainID)
    .map((action: ReadAllByDomainID) => action.payload)
    .switchMap(payload => this.probeHostService.readAllByDomainID(payload))
    .map(probeHosts => {
      return new ReadAllByDomainIDSuccess(probeHosts);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadAllByDomainIDFailure(error));
    });

  @Effect()
  Read$: Observable<Action> = this.actions$
    .ofType(ActionType.Read)
    .map((action: Read) => action.payload)
    .switchMap(payload => this.probeHostService.read(payload))
    .map(probeHost => {
      return new ReadSuccess(probeHost);
    })
    .catch((error: RPCClientError) => {
      return of(new ReadFailure(error));
    });

    @Effect()
    Modify$: Observable<Action> = this.actions$
      .ofType(ActionType.Modify)
      .map((action: Modify) => action.payload)
      .switchMap(payload => this.probeService.modify(payload))
      .map(probe => {
        return new ModifySuccess(probe);
      })
      .catch((error: RPCClientError) => {
        return of(new ModifyFailure(error));
      });
}
