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 { RESTClientError } from '@loafer/ng-rest/protocol';
import { MemberTotpService } from '../../service/member-totp.service';

import {
  CreateTotp,
  CreateTotpSuccess,
  CreateTotpFailure,

  Regist,
  RegistSuccess,
  RegistFailure,

  CheckCodeForMember,
  CheckCodeForMemberSuccess,
  CheckCodeForMemberFailure,

  ActionType,
} from './totp.action';

@Injectable()
export class Effects {
  private _returnURL: any;

  constructor(
    private actions$: Actions,
    private memberTotpService: MemberTotpService,
    private router: Router
  ) { }

  @Effect()
  createTotp$: Observable<Action> = this.actions$
    .ofType(ActionType.CreateTotp)
    .map((action: CreateTotp) => action.payload)
    .switchMap(payload => {
      // this._returnURL = payload.returnURL;
      return this.memberTotpService.createTotp(payload);
    })
    .map((result: any) => {
      const key = result['key'];
      const uri = result['uri'];
      return new CreateTotpSuccess({key: key, uri: uri});
    })
    .catch((error: RESTClientError) => {
      return of(new CreateTotpFailure(error));
    });

  @Effect()
  regist: Observable<Action> = this.actions$
    .ofType(ActionType.Regist)
    .map((action: Regist) => action.payload)
    .switchMap((payload) => {
      // this._returnURL = payload.returnURL;
      return this.memberTotpService.regist(payload.member, payload.secretCode, payload.code);
    })
    .map((result: any) => {
      return new RegistSuccess(result);
    })
    .catch((error: RESTClientError) => {
      return of(new RegistFailure(error));
    });


  @Effect()
  checkCodeForMember: Observable<Action> = this.actions$
    .ofType(ActionType.CheckCodeForMember)
    .map((action: Regist) => action.payload)
    .switchMap((payload) => {
      // this._returnURL = payload.returnURL;
      return this.memberTotpService.checkCodeForMember(payload.member, payload.code);
    })
    .map((result: any) => {
      return new CheckCodeForMemberSuccess(result);
    })
    .catch((error: RESTClientError) => {
      return of(new CheckCodeForMemberFailure(error));
    });
}
