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 { Target } from '../../model';
import { TargetService } from '../../service/target.service';

import {
  ReadAllByDomain,
  ReadAllByDomainSuccess,
  ReadAllByDomainFailure,
  ActionType,
} from './target.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private targetService: TargetService,
    private router: Router
  ) { }

  @Effect()
  readAllByMember$: Observable<Action> = this.actions$
    .ofType(ActionType.ReadAllByDomain)
    .map((action: ReadAllByDomain) => action.payload)
    .exhaustMap(domain =>
      this.targetService
      .readAllByDomain(domain)
        .map(targets => new ReadAllByDomainSuccess(targets))
        .catch(error => of(new ReadAllByDomainFailure(error)))
    );

}
