import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { Effect, Actions } 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 { MemberService } from '../../service/member.service';

import {
  ResetPassword,
  ResetPasswordSuccess,
  ResetPasswordFailure,
  ModifyPassword,
  ModifyPasswordSuccess,
  ModifyPasswordFailure,
  ActionType
} from './reset-password.action';

@Injectable()
export class Effects {

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

  @Effect()
  ResetPassword$: Observable<Action> = this.actions$
    .ofType(ActionType.ResetPassword)
    .map((action: ResetPassword) => action.payload)
    .exhaustMap(payload =>
      this.memberService
        .sendEmailResetPassword(payload)
        .map(_member => new ResetPasswordSuccess(_member))
        .catch(error => of(new ResetPasswordFailure(error)))
    );

  @Effect()
  ModifyPassword$: Observable<Action> = this.actions$
    .ofType(ActionType.ModifyPassword)
    .map((action: ModifyPassword) => action.payload)
    .exhaustMap(payload =>
      this.memberService
        .resetPassword(payload.token, payload.pw, payload.confirmPw)
        .map(_member => new ModifyPasswordSuccess(_member))
        .catch(error => of(new ModifyPasswordFailure(error)))
    );
  //
  // @Effect({ dispatch: false })
  // ResetPasswordSuccess$ = this.actions$
  //   .ofType(ActionType.ResetPasswordSuccess)
  //   .do(() => this.router.navigate(['/']));

}
