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 { Member } from '@overflow/commons-typescript/model/member';
import { MemberService } from '../../service/member.service';

import {
  Signup,
  SignupSuccess,
  SignupFailure,
  ActionType,
} from './signup.action';

@Injectable()
export class Effects {

  constructor(
    private actions$: Actions,
    private memberService: MemberService,
    private router: Router
  ) { }

  @Effect()
  signup$: Observable<Action> = this.actions$
    .ofType(ActionType.Signup)
    .map((action: Signup) => action.payload)
    .exhaustMap(payload =>
      this.memberService
        .signup(payload.member, payload.password)
        .map(_member => new SignupSuccess(_member))
        .catch(error => of(new SignupFailure(error)))
    );

  @Effect({ dispatch: false })
  signupSuccess$ = this.actions$
    .ofType(ActionType.SignupSuccess)
    .do(() => this.router.navigate(['/']));

}
