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 {
  DiscoverZone,
  DiscoverHost,
  DiscoverPort,
  DiscoverService,
  ActionType
} from './discover.action';
import {DiscoveryService} from '../../service/discovery.service';


@Injectable()
export class Effects {

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

  @Effect({ dispatch: false })
  discoveryZone$ = this.actions$
    .ofType(ActionType.DiscoverZone)
    .map((action: DiscoverZone) => action.payload)
    .do(payload => {
      this.discoveryService.discoverZone(payload.probeID, payload.discoverZone);
    });

  @Effect({ dispatch: false })
  discoveryHost$ = this.actions$
    .ofType(ActionType.DiscoverHost)
    .map((action: DiscoverHost) => action.payload)
    .do(payload => {
      this.discoveryService.discoverHost(payload.probeID, payload.zone, payload.discoverHost);
    });

  @Effect({ dispatch: false })
  discoveryPort$ = this.actions$
    .ofType(ActionType.DiscoverPort)
    .map((action: DiscoverPort) => action.payload)
    .do(payload => {
      this.discoveryService.discoverPort(payload.probeID, payload.host, payload.discoverPort);
    });

  @Effect({ dispatch: false })
  discoveryService$ = this.actions$
    .ofType(ActionType.DiscoverService)
    .map((action: DiscoverService) => action.payload)
    .do(payload => {
      this.discoveryService.discoverService(payload.probeID, payload.port, payload.discoverService);
    });
}
